I have some services in my asp.net mvc application that listen for AMQP messages and invoke methods.
No controllers depend on this, so it won't get instantiated on its own.
I could instantiate it manually, explicitly providing its dependencies with kernel.Get but it feels like I shouldn't have to do that.
Can I make Ninject instantiate classes in singleton scope eagerly even when nothing else depends on it?
You cannot have ninject instantiate stuff in case you don't ask it to instantiate something yourself.
The simple way is to ask ninject to instantiate things at composition root:
var kernel = new StandardKernel();
kernel.Bind<IFoo>().To<Foo>();
kernel.Load(AppDomain.CurrentDomain.GetAssemblies()); // loads all modules in assemlby
//...
// resolution root completely configured
kernel.Resolve<IFooSingleton>();
kernel.Resolve<IBarSIngleton>();
There is one alternative, actually, which is not the same, but can be used to achieve a similar effect. It requires that there is at least one single other service instantiated soon enough: Ninject.Extensions.DependencyCreation.
It works like this:
kernel.Bind<string>().ToConstant("hello");
kernel.Bind<ISingletonDependency>().To<SingletonDependency>()
.InSingletonScope();
kernel.DefineDependency<string, ISingletonDependency>();
kernel.Get<string>();
// when asking for a string for the first time
// ISingletonDependency will be instantiated.
// of course you can use any other type instead of string
Why
Ninject is unlike some other containers (for example Autofac) not "built" in stages. There's no concept of first creating the bindings, and then creating the kernel to use them. The following is perfectly legal:
kernel.Bind<IFoo>()...
kernel.Get<IFoo>()...
kernel.Bind<IBar>()...
kernel.Get<IBar>()...
so ninject can't possibly know when you want the singletons to be instantiated. With autofac it's clear and easy:
var containerBuilder = new ContainerBuilder();
containerBuilder
.RegisterType<Foo>()
.AutoActivate();
var container = containerBuilder.Build(); // now
Coming from Guice in Java, I've sorely missed the pattern of eager singletons. They are useful in scenarios where for example modules act as plugins. If you imagine that a service is assembled from modules that are specified in a configuration, you could see a problem of then also trying to specify what this module needs to be auto-instantiated when the application is started.
For me the module is where the composition of the application is defined and separating eager singletons into another place in the code feels more clunky and less intuitive.
Anyway, I've been able to very easily implement this as a layer on top of Ninject, here's the code:
public static class EagerSingleton
{
public static IBindingNamedWithOrOnSyntax<T> AsEagerSingleton<T>(this IBindingInSyntax<T> binding)
{
var r = binding.InSingletonScope();
binding.Kernel.Bind<IEagerSingleton>().To<EagerSingleton<T>>().InSingletonScope();
return r;
}
}
public interface IEagerSingleton { }
public class EagerSingleton<TComponent> : IEagerSingleton
{
public EagerSingleton(TComponent component)
{
// do nothing. DI created the component for this constructor.
}
}
public class EagerSingletonSvc
{
public EagerSingletonSvc(IEagerSingleton[] singletons)
{
// do nothing. DI created all the singletons for this constructor.
}
}
After you've created your kernel, add a single line:
kernel.Get<EagerSingletonSvc>(); // activate all eager singletons
You use it in a module like this:
Bind<UnhandledExceptionHandlerSvc>().ToSelf().AsEagerSingleton();
Related
I think I'm missing a key part of how to actually use IoC/DI. I happen to be using the Unity container. I know how to setup a class to have it's dependencies injected and I also know how to make Unity register a type.
But what I don't know is how to actually then make use of these registrations.
So for example:
var container = new UnityContainer();
container.RegisterType<IRepository, XmlRepository>();
var service = new MyService(container.Resolve<IRepository>());
public interface IRepository
{
void GetStuff();
}
public class XmlRepository : IRepository
{
public void GetStuff()
{
throw new NotImplementedException();
}
}
public class MyService
{
private readonly IRepository _myRepository;
public MyService(IRepository repository)
{
_myRepository = repository;
}
}
Here I have a service layer which accepts a parameter of type IRepository. It's the container part that I seem to not be understanding.
Isn't the point of IoC/DI to be able to not have to manually resolve types every time I need to create an instance? In my code I'm getting the container to resolve a type, unless I'm misunderstanding how this is supposed to work, isn't the container supposed to somehow automatically (with reflection?) inject the dependency I told it to use when I registered the type? var service = new MyService(...) Is calling container.Resolve the correct way of doing this?
I've created a container, but how do I share this container amongst my project/code? This sort of relates to the first question. I had previously thought that there was a single place that you register types. So far the only way I can see how to get around this is to:
Keep registering types wherever I use them and end up with duplicated code
Pass the container around to every place I'm going to be resolving types
Neither of these ways are how I'd expect this to work
Isn't the point of IoC/DI to be able to not have to manually resolve types every time I need to create an instance?
No, that's the point of a DI Container, but there are drawbacks to using a container as well. Favour Pure DI over using a DI Container, as this will teach you how to use Dependency Injection using only first principles.
I've created a container, but how do I share this container amongst my project/code?
You don't. The DI Container should only be used in the Composition Root (if you use a DI Container at all).
Put your container setup in a module that runs when your program starts. You can call it from Main, for example. This is called a boot strapper.
See Dependency Injection with Unity for a good example of how to do this.
You don't need to do new MyService(container.Resolve<IRepository>()). To get an instance of MyService, just use container.Resolve<MyService>(); it will automatically resolves the dependencies for MyService.
I have implemented a solution that has some core reusable classes that are easily registered and resolved using StructureMap. I then have an abstract factory to load additional families of products at runtime.
If I have a StructureMap registries like this one:
public ProductAClaimsRegistry()
{
var name = InstanceKeys.ProductA;
this.For<IClaimsDataAccess>().LifecycleIs(new UniquePerRequestLifecycle()).Use<ProductAClaimsDataAccess>().Named(name)
.Ctor<Func<DbConnection>>().Is(() => new SqlConnection(ConfigReader.ClaimsTrackingConnectionString));
this.For<IClaimPreparer>().LifecycleIs(new UniquePerRequestLifecycle()).Use<ProductAClaimPreparer>().Named(name);
this.For<IHistoricalClaimsReader>().LifecycleIs(new UniquePerRequestLifecycle()).Use<ProductAHistoricalClaimReader>().Named(name);
this.For<IProviderClaimReader>().LifecycleIs(new UniquePerRequestLifecycle()).Use<ProductAProviderClaimReader>().Named(name);
}
There may be a version for ProductB, ProductC and so on.
My abstract factory then loads the correct named instance like this:
public abstract class AbstractClaimsFactory
{
private IClaimsReader claimsReader;
private IClaimPreparer claimPreparer;
protected string InstanceKey { get; set; }
public virtual IClaimsReader CreateClaimReader()
{
return this.claimsReader;
}
public virtual IClaimPreparer CreateClaimPreparer()
{
return this.claimPreparer;
}
public void SetInstances()
{
this.CreateInstances();
var historicalReader = ObjectFactory.Container.GetInstance<IHistoricalClaimsReader>(this.InstanceKey);
var providerReader = ObjectFactory.Container.GetInstance<IProviderClaimReader>(this.InstanceKey);
this.claimsReader = new ClaimsReader(historicalReader, providerReader);
this.claimPreparer = ObjectFactory.Container.GetInstance<IClaimPreparer>(this.InstanceKey);
}
protected abstract void CreateInstances();
}
At runtime there is a processor class that has a concrete factory injected like this:
public void Process(AbstractClaimsFactory claimsFactory)
{
// core algorithm implemented
}
A concrete factory then exists for each product:
public class ProductAClaimsFactory : AbstractClaimsFactory
{
public ProductAClaimsFactory()
{
SetInstances();
}
protected override void CreateInstances()
{
InstanceKey = InstanceKeys.ProductA;
}
}
EDIT
The classes loaded in the factory are used by other classes that are Product agnostic - but they need to inject ProductA or ProductB behaviour.
public ClaimsReader(IHistoricalClaimsReader historicalClaimsReader, IProviderClaimReader providerClaimsReader)
{
this.historicalClaimsReader = historicalClaimsReader;
this.providerClaimsReader = providerClaimsReader;
}
I'm not exactly sure if this a text book abstract factory pattern and I'm new to StructureMap and more advance DI in general.
With this solution I think I have enforced a core algorithm and reused code where appropriate.
I also think that it is extensible as ProductN can easily be added without changing existing code.
The solution also has very good code coverage and the tests are very simple.
So, bottom line is: I am fairly happy with this solution but a colleague has questioned it, specificly around using ObjectFactory.Container.GetInstance<IClaimPreparer>(this.InstanceKey); to load named instances and he said it looks like the Service Locator anti pattern.
Is he correct?
If so, can anyone point out the downsides of this solution and how I might go about improving it?
This is service location. It's a problem as you have introduced a dependency on your service locator, ObjectFactory, rather than the interface, IClaimPreparer, your AbstractClaimsFactory class actually needs. This is going to make testing harder as you'll struggle to fake an implementation of IClaimPreparer. It also clouds the intention of your class as the class's dependencies are 'opaque'.
You need to look into the use of a Composition Root to resolve the anti-pattern. Have a look at Mark Seemann's work to find out more.
He's partially correct. Given a good DI container it is possible to register all your components and resolve the root object in your object tree... the DI container handles creating all the dependency for the root object (recursively) and creates the whole object tree for you. Then you can throw the DI container away. The nice thing about doing it that way is all references to DI container are confined to the entry-point of your app.
However, you are at least one step ahead of the curve since you didn't resolve dependencies in the constructor (or somewhere else) of the object using them, but instead resolved those in the factory and passed them in to the objects that need them via constructor-injection ;) (That's something I see often in code I work on and that is definitely an anti-pattern.
Here's a bit more about service locators and how they can be an anti-pattern:
http://martinfowler.com/articles/injection.html
http://blog.ploeh.dk/2010/02/03/ServiceLocatorisanAnti-Pattern/
Here's a bit more about the configure-resolve-release type pattern I hinted at:
http://blog.ploeh.dk/2010/08/30/Dontcallthecontainer;itllcallyou/
http://kozmic.net/2010/06/20/how-i-use-inversion-of-control-containers/
I'm just getting started with IoC containers and have picked up Ninject to start with. I understand the principle of the separate modules you can incorporate into a Kernel. But I'm curious if I should have the first line below everywhere in my code where I'm about to ask for the concrete implementation of something from my service layer.
IKernel kernel = new StandardKernel(new SimpleModule());
// example: getting my ContentService
IContentService contentService = kernel.Get<IContentService>();
If I have a class with 10 methods that use the ContentService should I really new up a Module and a Kernel in every method? Seems like a code smell. How do most developers handle this with Ninject? Are there any articles online that show the proper way to do this with the consumer class?
If I have a class with 10 methods that use the ContentService should I
really new up a Module and a Kernel in every method?
No, you should have this class take IContentService as constructor parameter (since it depends on it inside its methods) and then ask the kernel to provide you the instance of this class. Your classes should know nothing about the DI container (Ninject in your case). They should never reference it.
There are, basically two ways of working with IoC: Dependency Injection (DI) and Service Location (SL).
When dealing with dependecy injection, you provide you dependencies from outside your classes. Generally, you do this by injecting (passing) your dependencies into the class constructor or by using setters. For example:
public class SomeClass {
public ISomeDependency SomeDependency {get;set;}
public SomeClass(ISomeOtherDependecy someOtherDependency) {
//...
}
}
In this case, you COULD provide a ISomeDependency implementation through the property and you SHOULD provide ISomeOtherDependecy implementation through the constructor. Ninject support both ways.
The other way of doing (SL) allows you to request for your dependencies in the moment you need, for example:
public void DoSomeAction() {
ISomeDependency someDependency = MyServiceLocatorImpl.GetInstance<ISomeDependence>()
}
If you plan to use the SL approach (or an hybrid one), you could use the Common Service Locator (Ninject has support for it) . It makes easy to switch our IoC engine later.
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.
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());
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.
I'm a complete newbie to ninject
I've been pulling apart someone else's code and found several instances of nInject modules - classes that derive from Ninject.Modules.Module, and have a load method that contains most of their code.
These classes are called by invoking the LoadModule method of an instance of StandardKernel and passing it an instance of the module class.
Maybe I'm missing something obvious here, but what is the benefit of this over just creating a plain old class and calling its method, or perhaps a static class with a static method?
The Ninject modules are the tools used to register the various types with the IoC container. The advantage is that these modules are then kept in their own classes. This allows you to put different tiers/services in their own modules.
// some method early in your app's life cycle
public Kernel BuildKernel()
{
var modules = new INinjectModule[]
{
new LinqToSqlDataContextModule(), // just my L2S binding
new WebModule(),
new EventRegistrationModule()
};
return new StandardKernel(modules);
}
// in LinqToSqlDataContextModule.cs
public class LinqToSqlDataContextModule : NinjectModule
{
public override void Load()
{
Bind<IRepository>().To<LinqToSqlRepository>();
}
}
Having multiple modules allows for separation of concerns, even within your IoC container.
The rest of you question sounds like it is more about IoC and DI as a whole, and not just Ninject. Yes, you could use static Configuration objects to do just about everything that an IoC container does. IoC containers become really nice when you have multiple hierarchies of dependencies.
public interface IInterfaceA {}
public interface IInterfaceB {}
public interface IInterfaceC {}
public class ClassA : IInterfaceA {}
public class ClassB : IInterfaceB
{
public ClassB(IInterfaceA a){}
}
public class ClassC : IInterfaceC
{
public ClassC(IInterfaceB b){}
}
Building ClassC is a pain at this point, with multiple depths of interfaces. It's much easier to just ask the kernel for an IInterfaceC.
var newc = ApplicationScope.Kernel.Get<IInterfaceC>();
Maybe I'm missing something obvious
here, but what is the benefit of this
over just creating a plain old class
and calling its method, or perhaps a
static class with a static method?
Yes, you can just call a bunch of Bind<X>().To<Z>() statements to setup the bindings, without a module.
The difference is that if you put these statements in a module then:
IKernel.Load(IEnumerable<Assembly>) can dynamically discover such modules through reflection and load them.
the bindings are logically grouped together under a name; you can use this name to unload them again with IKernel.Unload(string)
Maybe I'm missing something obvious here, but what is the benefit of this over just creating a plain old class and calling its method, or perhaps a static class with a static method?
For us, it is the ability to add tests at a later time very easily. Just override a few bindings with mockobjects and voila.....on legacy code without a DI that wired "everything" up, it is near impossible to start inserting test cases without some rework. With a DI in place AND as long as it was used properly where the DI wired everything up, it is very simple to do so even on legacy code that may be very ugly.
In many DI frameworks, you can use the production module for your test with a test module that overrides specific bindings with mockobjects(leaving the rest of the wiring in place). These may be system tests more than unit tests, but I tend to prefer higher level tests than the average developer as it tests the integration between classes and it is great documentation for someone who joins the project and can see the whole feature in action(instead of just parts of the feature) without having to setup a whole system).