Question

As per my understanding, implementation of DI based on

1. ISampleInterface

2. Sample : ISampleInterface

3. Configuration Bind for ISampleInterface with Sample.

4. And Constructor injection

ISampleInterface _sampleInterface;

Constructor(ISampleInterface sampleInterface)
{
  _sampleInterface = sampleInterface;
}

Rest of the thing handle by DI.

But if some case, within concrete Interface implementation class, it may be required to "New" Initialization. Then What Should I do ?

Within Sample class,

If I required to declare

private const int _limitSize = 70;
limits = new int[_limitSize];

Or within Sample class. bellow code may be required to write for Interface method implementation.

Dictionary<string, object[]> arr = new Dictionary<string, object[]>()
{       
    {"name", new string[1]{listName}},          
};

Actual Implementation

public string ContactListsAdd(string listName)
{
    Dictionary<string, object[]> arr = new Dictionary<string, object[]>()
    {       
        {"name", new string[1]{listName}},          
    };

    return callSomePrivateMethod("contact-lists.add", arr);         
}

So My question is that, Is it a right approach to create object manually when we use DI. As per example. Or is their any way to avoid that ?

Was it helpful?

Solution

There is nothing bad about manually creating objects (like data structures or general purpose objects), that you need to implement your business logic. However, they should be encapsulated inside your bussines logic implementation. What you should not create manually are business components (like repositories, services etc.)

Dependency injection pattern is here to provide you a way how to achieve loose coupling of components. It turns the responsibility of creating such components to DI container, so you do not need to mess with creating such components inside your bussiness logic (it could be quite useful even if you do not tend to use loose-coupling, when the creation of such component become complex). However, I would not recommend to move the responsibility of creating all objects you use towards the DI container. In the end the registration (binding) of components could become:

Bind<IList<string>>().To<List<string>>();
Bind<IList<int>>().To<List<int>>();
Bind<IList<MyObject>>.To<MyObject>(); // what about constructor arguments ???
... and other mess of bindings

It would be very hard to maintain such bindings. And what if you need to use different size or different implementation of list? Where would you get constructor arguments for some inner class object? Of course, you can use conditional binding, but it would then become one big conditional binding mess.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top