I am just starting to use Ninject on a (large) project and am wading in by only using DI for a portion of it to start. I have a subsystem that is organized using constructor injection extensively. Using Ninject to inject all of the dependencies between classes in this subystem is working great. However, I have dependencies on things outside of the subystem that I would really like to use Ninject to automatically inject as well, but not to be in charge of their lifecycle.
I thought Bind<T>.ToConstant(...) would work for what I am trying to do. For instance, I may have a class of type Monkey that is to act as a Singleton, but another part of my application is handling its lifecycle without Ninject (for example, creating it and disposing it manually). When my Ninject-equipped subsystem gets created I instantiate a kernel, bind my subsystem classes, and then use something like Bind<Monkey>.ToConstant(Monkey.Instance) to bind to various "external" dependencies. This works great at activation time but does not work as needed when I dispose the kernel. My subsystem can have a shorter lifecycle than these external dependencies, but when I call Dispose on the kernel all of these dependencies get disposed, which is not what I want. While I can see arguments both ways, it seems a bit questionable that Ninject would automatically dispose an object that it did not create. I'm hoping there is at least a way to opt out of this behavior, but so far I have not found anything. Is there any support for this?
Add InTransientScope to your constant object.
Related
While working on a large legacy monolithic C# application we're now moving towards using an Event Aggregator for in app messaging. Up until now we've been using Dependency Injection directly passing dependencies into classes as needed.
The lifetime of those instances are configured and handled by the DI framework but introducing the Event Aggregator into this raises a few questions.
Let's say there is a completely isolated service class working way back in the stack and let's say that this class is called by the user very rarely. But when in use it must be as a singleton. Using DI straight up this is very easy (just inject the instance to whatever needs it, instantiate first if needed) but combining this with Event Aggregator I fail to see a natural way to manage the creation of the service class.
One alternative would be to always create the instance on app start and stuff it away somewhere. It works but it's no good always creating an instance that is almost never used. Furthermore where would be a neat place to hang on to it? I suppose, since this is a singleton, that it could be left to the DI framework to hang on to it but the questions still stands for transient instances of other similar classes.
Another alternative is that a EA message listener that creates instances as needed could be created, but I fail to see a way for this construct to automatically kill instances when not needed any longer. I guess this could be solved by adding messages to also end instances but now the overhead is getting silly.
Is this (DI and EA) a bad match for this situation or am I missing a neat way to solve these problems?
I'm moving from StructureMap 2.x to 3.x. One major change is that using ObjectFactory results in the following warning:
'StructureMap.ObjectFactory' is obsolete: 'ObjectFactory
will be removed in a future 4.0 release of StructureMap. Favor the
usage of the Container class for future
work'
So in most cases, the resolution is fairly easy: pass through IContainer as a constructor. Unfortunately this is not feasible for ASMX web serivces or attributes, both of which require a default constructor. That means I'm probably stuck with the Service Locator Pattern, property injection, or writing my own ObjectFactory implementation.
What's the preferred way to deal with this unfortunate problem?
Edit: It's worth mentioning that my container does an Assembly scan.
Per Jeremy Miller, himself:
Assembly scanning isn’t cheap and you (almost?) always wanna cache the
results. So, yeah, in that case you’re going to have to write your
own ObjectFactory. Someday all that bad old MS tech will go away.
So in this case, this implementation is what should be done.
The cleanest way I have seen to deal with this is to use .NET routing to take control of the entry point, then make a custom PageHandlerFactory implementation that takes the DI container as a dependency.
The custom page handler factory will then property inject the page/service after it is instantiated but before any of its events are called.
This is almost exactly the same way that IControllerFactory works with DI in MVC. In MVC, the container is injected into a custom IControllerFactory implementation at application startup, which effectively makes it a part of the application's composition root. In the case of ASP.NET, the IRouteHandler would effectively be part of the composition root.
I was unable to find a link to the source where I originally saw that implementation. But this one is pretty close. The primary difference is that one tries to use constructor injection, but the downside is that it requires full trust to do. I believe if you stick with property injection, you can do it with partial trust.
I'm building a MVC application with Autofac and EntityFramework. I have a large set of data repositories / business objects that use my logging interface (NLog). I have just started working with Autofac and would like to know the preferred way for property injection:
Pass ILogging as constructor property, for this I have to set each local property from the constructor and creates larger constructor footprints.
Register each object individually with Autofac (they do not share a generic interface)
Use an Autofac.Module to locate these objects and set the property with reflection
Create a generic interface ILoggerDependency and register this with Autofac, this way all objects are easely registred.
My preferred method (out of lazyness...) is to have a generic interface that I can register with Autofac.
I am not that familiar with Autofac, so I'll try to give you my best recommendation based on what I know.
If there is one thing a lot of people gets wrong with dependency injection, it has to be using it for automation. The goal of DI is not to remove magic from your code. If anything, it is quite the opposite.
Keeping that in mind, I would not even consider using reflection as it hides large amounts of fragile plumbing.
Next, interfaces in OOP are meant to express what an object can do. Being injected is definitely not an action an object can take, but rather something that is imposed on an object. Even though, it is a quick and dirty way to solve your issue, I would refrain from using it as it will denature the structure of your code.
I have trouble understanding what you mean by pass ILogging as constructor property. Basically, you mean to resolve the interface yourself in the constructor? This looks a lot like property injection which defeats the purpose of DI by adding a strong dependency on your container within your class. Basically, instead of depending on Log4Net, you end up depending on Autofac. To fix this, you would need to add a service locator and then you still end up with a similar problem. How do you inject your service locator?
This is why I would register each object individually. It lets your container do its job. It doesn't affect your code structure and abstractions. It doesn't uses reflection (magic). It doesn't force you to depend on your container within each class. Besides, it also gives you a centralized place to look for when adding or removing repositories from your code.
I'm currently using Ninject to handle DI on a C#/.Net/MVC application. When I trace the creation of instances of my services, I find that services are called and constructed quite a lot during a the life cycle, so I'm having to instantiate services and cache them, and then check for cached services before instantiating another. The constructors are sometimes quite heavy).
To me this seems ridiculous, as the services do not need unique constructor arguments, so instantiating them once is enough for the entire application scope.
What I've done as a quick alternative (just for proof-of-concept for now to see if it even works) is...
Created a static class (called AppServices) with all my service interfaces as it's properties.
Given this class an Init() method that instantiates a direct implementation of each service interface from my service library. This mimics binding them to a kernel if I was using Ninject (or other DI handler).
E.g.
public static class AppServices(){
public IMyService MyService;
public IMyOtherService MyOtherService;
public Init(){
MyService = new MyLib.MyService();
MyOtherService = new MyLib.MyOtherService();
}
}
On App_Start I call the Init() method to create a list of globally accessible services that are only instantiated once.
From then on, every time I need an instance of a service, I get it from AppServices. This way I don't have to keep constructing new instances that I don't need.
E.g.
var IMyService _myService = AppServices.MyService;
This works fine and I haven't had ANY issues arise yet. My problem is that this seems way too simple. It is only a few lines of code, creating a static class in application scope. Being as it does exactly what I would need Ninject to do, but in (what seems to me for my purposes) a much cleaner and performance-saving way, why do I need Ninject? I mean, these complicated dependency injection handlers are created for a reason right? There must be something wrong with my "simple" interpretation of DI, I just can't see it.
Can any one tell me why creating a global static container for my service instances is a bad idea, and maybe explain exactly what make Ninject (or any other DI handler) so necessary. I understand the concepts of DI so please don't try and explain what makes it so great. I know. I want to know exactly what it does under the hood that is so different to my App_Start method.
Thanks
Your question needs to be divided into two questions:
Is it really wrong to use the singleton pattern instead to inject dependencies?
Why do I need an IoC container?
1)
There are many reasons why you should not use the singleton pattern. Here are some of the major ones:
Testability
Yes you can test with static instances. But you can't test Isolated (FIRST). I have seen projects that searched a long time why tests start failing for no obvious reason until they realized that it is due to tests that were run in a different order. When you had that problem once you will always want your tests to be as isolated as possible. Static values couples tests.
This gets even worse when you also do integration/spec testing additional to unittesting.
Reusability
You can't simply reuse your components in other projects. Other projects will have to use that concept as well even if they might decide to use an IoC container.
Or you can't create another instance of your component with different dependencies. The components dependencies will be hard wired to the instances in your AppServices. You will have to change the components implementation to use different dependencies.
2) Doing DI does not mean that you have to use any IoC container. You can implement your own IDependencyResolver that creates your controllers manually and injects the same instance of your services wherever they are required. IoC containers use some performance but they simplyfy the creation of your object trees. You will have to decide yourself what matters more performance or simpler creation of your controllers.
I am currently using a library (SuperWebSocket) which is a websocket server library that use a bootstrap which know which instances to load from a configuration file. I have implemented a bootstrap class for this (however the instances arent loaded using IoC). Also the commands from this server are loaded from assemblies reflection. I wanted to use this server in conjonction with my DAL and service layer which use IoC. My main problem is that i can't find a way to put this Console Application (Server) and cooperation with the lib in an IoC scenario without having to end up using the ServiceLocator.
Normally the kernel (Ninject) should be located at the composition root (Look like to be the best practice from many around..) which is rather not possible to do in this case or at least i didn't found how so that why i am here. Also the commands are loaded from assemblies reflection. I could implement a CommandLoader however this is still a problem cause they all inherit from the same interface (Multibinding maybe?). I could make custom interface for each of them but i still can't find a way to load them automatically. Even if i found a way to load them, i still have to be able to get service from attributes which is not easy to do.
Any suggestions ?
If I understand your question correctly then the library is the entry point for all work done. In this situation it depends on the framework what to do. Here are some things you can do the first things are the preferred ones:
Inspect the library and find some way to hook into the framework to intercept the creation of your objects.
Call kernel.Inject(this) after an object is created by the library. Have a look at the Ninject.Web extension. There we added some base classes e.g. NinjectWebPage for WebPage. This new base class calls kernel.Inject after creation. New web pages can now be derived from that base class and use property injection to get dependencies.
Use the ServiceLocator pattern in the objects created by the libray. But just at this level. Anything deeper should use dependency injection.