Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having trouble understanding ninject (or just IOC container in general) over factory DI?

Okay, so recently I've been reading into ninject but I am having trouble understanding what makes it better over why they referred do as 'poor man's' DI on the wiki page. The sad thing is I went over all their pages on the wiki and still don't get it =(.

Typically I will wrap my service classes in a factory pattern that handles the DI like so:

public static class SomeTypeServiceFactory
{
    public static SomeTypeService GetService()
    {
        SomeTypeRepository someTypeRepository = new SomeTypeRepository();
        return = new SomeTypeService(someTypeRepository);

    }

}

Which to me seems a lot like the modules:

public class WarriorModule : NinjectModule {
    public override void Load() {
      Bind<IWeapon>().To<Sword>();
      Bind<Samurai>().ToSelf().InSingletonScope();
    }
}

Where each class would have it's associated module and you Bind it's constructor to a concrete implementation. While the ninject code is 1 less line I am just not seeing the advantage, anytime you add/remove constructors or change the implementation of an interface constructor, you'd have to change the module pretty much the same way as you would in the factory no? So not seeing the advantage here.

Then I thought I could come up with a generic convention based factory like so:

 public static TServiceClass GetService<TServiceClass>()
        where TServiceClass : class
    {
        TServiceClass serviceClass = null;

        string repositoryName = typeof(TServiceClass).ToString().Replace("Service", "Repository");
        Type repositoryType = Type.GetType(repositoryName);

        if (repositoryType != null)
        {
            object repository = Activator.CreateInstance(repositoryType);
            serviceClass =  (TServiceClass)Activator.CreateInstance(typeof (TServiceClass), new[]{repository});
        }

        return serviceClass;
    }

However, this is crappy for 2 reasons: 1) Its tightly dependent on the naming convention, 2) It assumed the repository will never have any constructors (not true) and the service's only constructor will be it's corresponding repo (also not true). I was told "hey this is where you should use an IoC container, it would be great here!" And thus my research began...but I am just not seeing it and am having trouble understanding it...

Is there some way ninject can automatically resolve constructors of a class without a specific declaration such that it would be great to use in my generic factory (I also realize I could just do this manually using reflection but that's a performance hit and ninject says right on their page they don't use reflection).

Enlightment on this issue and/or showing how it could be used in my generic factory would be much appreciated!

EDIT: Answer

So thanks to the explanation below I was ably to fully understand the awesomeness of ninject and my generic factory looks like this:

public static class EntityServiceFactory
{
    public static TServiceClass GetService<TServiceClass>()
        where TServiceClass : class
    {
        IKernel kernel = new StandardKernel();

        return kernel.Get<TServiceClass>();
    }
}

Pretty awesome. Everything is handled automatically since concrete classes have implicit binding.

like image 709
SventoryMang Avatar asked Jan 26 '12 16:01

SventoryMang


2 Answers

The benefit of IoC containers grows with the size of the project. For small projects their benefit compared to "Poor Man's DI" like your factory is minimal. Imagine a large project which has thousands of classes and some services are used in many classes. In this case you only have to say once how these services are resolved. In a factory you have to do it again and again for every class.

Example: If you have a service MyService : IMyService and a class A that requires IMyService you have to tell Ninject how it shall resolve these types like in your factory. Here the benefit is minimal. But as soon as you project grows and you add a class B which also depends on IMyService you just have to tell Ninject how to resolve B. Ninject knows already how to get the IMyService. In the factory on the other hand you have to define again how B gets its IMyService.

To take it one step further. You shouldn't define bindings one by one in most cases. Instead use convention based configuration (Ninject.Extension.Conventions). With this you can group classes together (Services, Repositories, Controllers, Presenters, Views, ....) and configure them in the same way. E.g. tell Ninject that all classes which end with Service shall be singletons and publish all their interfaces. That way you have one single configuration and no change is required when you add another service.

Also IoC containers aren't just factories. There is much more. E.g. Lifecycle managment, Interception, ....

kernel.Bind(
    x => x.FromThisAssembly()
          .SelectAllClasses()
          .InNamespace("Services")
          .BindToAllInterfaces()
          .Configure(b => b.InSingletonScope()));
kernel.Bind(
    x => x.FromThisAssembly()
          .SelectAllClasses()
          .InNamespace("Repositories")
          .BindToAllInterfaces());
like image 117
Remo Gloor Avatar answered Nov 02 '22 15:11

Remo Gloor


To be fully analagous your factory code should read:

public static class SomeTypeServiceFactory
{
    public static ISomeTypeService GetService()
    {
        SomeTypeRepository someTypeRepository = new SomeTypeRepository();

        // Somewhere in here I need to figure out if i'm in testing mode 
        // and i have to do this in a scope which is not in the setup of my
            // unit tests

        return new SomeTypeService(someTypeRepository);
    }

    private static ISomeTypeService GetServiceForTesting()
    {
        SomeTypeRepository someTypeRepository = new SomeTypeRepository();
        return new SomeTestingTypeService(someTypeRepository);
    }
}

And the equilvalent in Ninject would be:

public class WarriorModule : NinjectModule {
    public override void Load() {
      Bind<ISomeTypeService>().To<SomeTypeService>();
    }
}

public class TestingWarriorModule : NinjectModule {
    public override void Load() {
      Bind<ISomeTypeService>().To<SomeTestingTypeService>();
    }
}

Here, you can define the dependencies declaratively, ensuring that the only differences between your testing and production code are contained to the setup phase.

The advantage of an IoC is not that you don't have to change the module each time the interface or constructor changes, it's the fact that you can declare the dependencies declaratively and that you can plug and play different modules for different purposes.

like image 28
Slugart Avatar answered Nov 02 '22 15:11

Slugart