I am currently learning MVVM abd the tutorial I have been using, simply uses a single View Model with a single Model. The View Model is injected with the Model interface as such:
public ViewModel(IQuoteSource quoteSource)
{
}
This is handled via DI using Unity. My question is what if the VM is dependent on multiple Models, say an arbitrary 6 or 7? Do we simply inject each of them into the ctor or should there be seperate VM's for this?
Or should each model try to implement a specific interface that exposes a couple of methods/events such as register to hook into and then an event once the data has been updated?
Thanks.
That is a lot of models for your VM to depend on. You can inject all those on the constructor, this makes the dependence more explicit and visible. Or you can have the VM resolve the various models from the Unity container:
public ViewModel(IUnityContainer container)
{
IQuoteSource model1 = container.Resolve<IQuoteSource>();
... etc ...
}
When a concrete instance is resolved using Unity and you have not specified any constructor parameters in the Resolve() call, Unity will examine the constructors from most complicated to most basic, if it finds one that takes a Unity container then it will use it (it will potentially use others first if it finds them).1 So if your VM takes a Unity container in the constructor, it can then use that container to further resolve anything it needs.
Some may argue over which method is more suitable - direct injection of all required dependencies, or injecting just the container that has the dependencies. IMVHO there are positives and negatives to both approaches, use whichever suits your style better.
You could also consider refactoring your code somewhat, maybe introduce a new Model that is a facade over several existing models. The other possibility is what you have termed a Model may actually be more suitable as a service (a tell-tale sign of this is if the model is used in several places to fetch data from a specific source, if this is the case then you can separate out that functionality into a service and cart that around in the Unity container for it to be consumed as necessary).
1 Reference: Telling Unity Which Constructor to Use when Initializing a Class
Related
Reading the Simple injector docs to get a handle on how it all works and I read the below paragraph. I understand what its explaining apart from the part in bold. What does it mean?
The technique for keeping this dependency to a minimum can be achieved by designing the types in your application around the constructor injection pattern: Define all dependencies of a class in the single public constructor of that type; do this for all service types that need to be resolved and resolve only the top most types in the application directly (i.e. let the container build up the complete graph of dependent objects for you)
Ignoring my lack of understanding regarding the sentence above I ploughed on but when trying to set up Simple injector for Web api came across this line of code container.RegisterWebApiControllers(GlobalConfiguration.Configuration); With this explanation
Because controllers are concrete classes, the container will be able to create them without any registration.
Does this mean if I have a bunch of classes that don't rely on an interface, I can create them using a single line of code? (if so how, should I).
What this means is a good practice of not relying on the DI-container in your code apart from some top-level where you have to do that to "kick-start" the application.
That will mean that all your classes will just have constructor dependencies in the form of interfaces and will not do Container.Resolve. This will only be called on the top level of you application.
In some frameworks you won't even have to do that yourself because it's a part of how framework operates. As far as I remember in .Net core e.g. you won't need to do a resolve, but it will happen inside framework when the controllers will be initiated.
Because controllers are concrete classes, the container will be able
to create them without any registration.
This means you won't have to register the controllers themselves in the container. Container will only resolve controller dependencies themselves, create controllers and pass all of the resolved dependencies in them.
P.S. Resolving only in the root of you application is nothing specific for the SimpleInjector. It is a good practice that can be applied to any container and SimpleInjector can be used even if you don't follow it, which probably no one these days would recommend.
do this for all service types that need to be resolved and resolve only the top most types in the application directly
What this means is that, once you solely use Constructor Injection as a way for a class to get a hold of its dependencies, you will end up building object graphs that are potentially many layers deep. Take this object graph for instance:
new HomeController(
new ProductService(
new SqlProductRepository(
new CommerceContext(connectionString)),
new AspNetUserContextAdapter(
httpContextAccessor)));
PRO TIP: Did you know that you can let Simple Injector visualize your object graphs for you inside the debugger? This is explained here.
Here you see that HomeController has one dependency (IProductService) that it gets through its constructor. ProductService itself has two dependencies (IProductRepository and IUserContext) that are as well supplied through its constructor. This can go many layers deep.
Having Constructor Injection as the sole means to supply dependencies to a class means that the class is not allows to request them itself by calling back into the Container. This is a well-established anti-pattern called Service Locator. Constructor Injection simplifies your classes and allows the Container to analyze the object graph for you and detect any anomalies.
and resolve only the top most types in the application directly
When the whole object graph is constructed using Constructor Injection, it means that you only have to ask for a HomeController, which is the top most type in the graph. Nothing depends on HomeController; HomeController depends on everything (implicitly). All application behavior is invoked through these top most types. In an MVC application these typically are controllers, HTTP handlers and modules.
Because controllers are concrete classes, the container will be able to create them without any registration.
This statement is a bit misleading. Yes, it is true that Simple Injector will be able to create a requested concrete type for you, even if that type isn't registered. As explained here in the documentation however, it is best to always register your root types in the container. This ensures that the container knows about those types and it allows analysis and verification on those types as well. Not registering those concrete root types will give you a false sense of security when you call container.Verify(). Verify is only able to verify on the registrations that it knows of. When an unregistered concrete type is referenced as a dependency, the container still knows about it, but that obviously doesn't hold for root types, since nothing depends on them.
WARNING: In Simple Injector v5, this behavior is likely going to change. By default, Simple Injector v5 will probably not allow concrete unregistered root types to be resolved. see
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 have three layers in my solution, Presentation (winforms project), Domain (class lib) and Persistence (class lib).
I am trying to implement dependency injection to decouple them.
My application root is in my presentation layer.
I understand the only time the DI container (unity in this case) should be referenced is in my application root, otherwise I would be simply replacing class dependencies all over the place with a dependency on my DI container (which I suppose is still slightly better).
So with these foundation concepts in mind, I am really struggling with the specific implementation. Perhaps my application root should be in its own seperate project - perhaps a console application. I can then resolve the first 'overallApplication' class, listing IPresentation, IDomain and IPersistence in its constructors. I understand (assuming actual implementations have been registered) the unity framework would then recursively solve all respective sub-dependencies.
In your experience - would you be able to advise if this was a sound approach. I really understand the concept and importance of decoupling, and how this is solved by DI conceptually at a high level, but I am struggling to tie it all together in a real application solution with multiple layers (organised in VS as seperate projects).
Any help or pointers towards examples of proper implementations would be greatly appreciated.
Some thoughts for you in hope that they help.
Throughout your question you make statements such as:
"I really understand the concept and importance of decoupling, and how this is solved by DI..."
The first thing I would evaluate is the understanding that DI != IoC Container (e.g. Unity).
An IoC container is used to remove boilerplate code that results from an existing DI structure. As such I would suggest you refactor without Unity /first/. Then go back and add Unity to reduce your code.
So that:
-1. Make application Di via manual Ctor, Property, Method, Service Locator injection methods.
-2. After this is setup you should see things like:
public View() {
var controller = new Controller(new IView(), new model(), new IService(new Dal(ISession(connectionString))), new , new ILogger(), etc.){}
}
-3. Then once you have something like this in your code you can then use Unity to inject all that fun:
public View() {}
Controller Controller {get;set;} //<- Unity auto builds & populates this for you with all the "new" items normally found in your constructor (or wherever).
While not a production example, it should give an idea of some steps to refactor. Going straight to Unity will put the cart before the horse, so to speak.
I am aware that a thousand and one questions relating to this topic have been asked, but I have gone through at least a dozen and am still not connecting the dots. I am trying to setup dependency injection for entity contexts.
I have always created my entity context as I have seen in the MS tutorials, like so:
public class UserController : Controller
{
private DbEntities db = new DbEntities();
}
Recent reading has told me that this is no longer (if it ever was) the best practice, and a dependency injection method should be used. Ninject is mentioned often, but I am seeing how you move from what I have, to the example give in the Ninject documentation.
It should look like this when I am done, right?
public class UserController : Controller
{
private DbEntities db;
public UserController(DbEntities context)
{
db = context;
}
}
The documentation starts out with "In the previous step we already prepared anything that is necessary for controller injection." which is confusing as hell, since the previous step was installation. I used the Nuget method to install, but I don't know what it means when it says "Now load your modules or define bindings in RegisterServices method." How do I do that, and is entity a module or a binding? The documentation feels so sparse.
I am sorry if I skipped over something critical in the docs, I've been bouncing between forums for hours trying to figure out this one step.
I used the Nuget method to install, but I don't know what it means
when it says "Now load your modules or define bindings in
RegisterServices method." How do I do that, and is entity a module or
a binding?
The Nuget installation actually does quite a lot of things for you already. The most important thing is that it sets up Ninject as controller factory, which means that Ninject will create your controllers and is able to pass in all dependencies you have registered with it.
If you check the App_Start folder you will find a file NinjectMVC3.cs. There is already an empty method RegisterServices() which you can use to register your dependencies.
For your example you must be able to resolve DbEntities. The easiest most basic way to do this is:
kernel.Bind<DbEntities>().ToSelf();
That said you really should pass in an interface to your controller so the controller does not depend on Entity Framework, using abstractions and registering a concrete class to use in the IoC container is one of the main reasons for dependency injection.
This should give you a start - the documentation you link to seems a bit outdated. I would recommend looking at the Ninject MVC3 sample on github.
Dependency Injection can seem confusing at first, but it's really actually quite simple.
A Dependency Injection "container" is basically a generic factory, with various object lifetime management features. Ninject, in particular, uses the syntax kernel.Bind() to confgure this factory. When you say kernel.Bind<DbEntities>().ToSelf() this means that Ninject will create an instance of the bound type (DbEntities in this case) whenever that type is requested. This request typically looks like this:
var entities = kernel.Get<DbEntities>(); // Note: don't do this, just an example
At it's core, this is what Dependency Injection is. A generic factory that can instantiate arbitrary types.
However, there is a lot more to it than that. One nice feature of Dependency Injection is that it will also instantiate any dependent types in the process. So, suppose you have a controller, and that controller has a dependency on DbEntities. Well, when a controller is instantiated by the DI Framework, it will also instantiate the dependent DbEntities. See the code below. When the MyController is instantiated, the DbEntities will automatically get instantiated (assuming you have bound the DbEntities class to self in the DI Configuration)
var controller = kernel.Get<MyController>();
public class MyController : Controller {
private DbEntities _entities;
public MyController(DbEntities entities) {
_entities = entities;
}
}
This is recursive. Any class that gets instantiated that has any objects that it itself might depend on get instantiated as well, and so on, and so on until finally, everything has what it needs to do its job.
Now, the great thing about MVC is that it has a way built-in to use any DI container automatically. You don't have to call kernel.Get because the framework does it for you when it creates the controllers when a request comes in. This feature is called IDependencyResolver, and is an interface that the MVC framework uses to allow third party DI containers to be used by the framework.
If you install Ninject by using the Nuget package Ninject.MVC3 then it will automatically configure all this for you, and you need only add your bindings to the RegisterServices() section of NinjectMVC3.cs
There's a lot more to it than this, but this should give you a basic understanding. Dependency Injection allows you to forget about the details of managing when objects are created and destroyed, you just specify in your constructor which dependencies you need, and assuming you have bindings for them in your configuration, MVC will take care of creating and destroying them for you. You just use them.
EDIT:
To be clear, I don't recommend you use the examples I give above. They are just simple illustrations of how DI works. In particular, the Get() syntax is known as "Service Location" and is considered to be bad. However, ultimately some code, somewhere must call Get(), it's just buried deep in the framework.
As Adam mentions, binding directly to the data entities context isn't a great idea, and you should eventually move to using an interface based approach.
I would never inject a concrete type here - you are directly coupling to a data access implementation.
Instead bind to IDbContext (or IUnitOfWork) - these are interfaces you define with a backing concrete implementation of DbContext, this way you can easily abstract away what technology you are using, making it more swappable, testable, maintainable, etc.
for ex:
http://blogs.planetcloud.co.uk/mygreatdiscovery/post/EF-Code-First-Common-Practices.aspx#disqus_thread
I have a class which is going to need to use the strategy design pattern. At run time I am required to switch different algorithms in and out to see the effects on the performance of the application.
The class in question currently takes four parameters in the constructor, each representing an algorithm.
How using Ninject (or a generalised approach) could I still use IOC but use the strategy pattern?
The current limitation is that my kernel (container) is aware of each algorithm interface, but that can only be bound to one concrete class. The only way around this I can see at the moment is pass in all eight algorithms at construction, but use different interfaces, but this seems totally uncessary. I wouldn't do this if I was not using an IOC container, so there must be some way around this.
Code example:
class MyModule : NinjectModule
{
public override void Load()
{
Bind<Person>().ToSelf();
Bind<IAlgorithm>().To<TestAlgorithm>();
Bind<IAlgorithm>().To<ProductionAlgorithm>();
}
}
Person needs to make use of both algorithms so I can switch at run time. But only TestAlgorithm is bound, as it's the first one in the container.
Let's take a step back and examine a slightly bigger picture. Since you want to be able to switch Strategy at run-time, there must be some kind of signalling mechanism that tells Person to switch the Strategy. If you application is UI-driven, perhaps there a button or drop-down list where the user can select which Strategy to use, but even if this is not the case, some outside caller must map a piece of run-time data to an instance of the Strategy.
The standard DI solution when you need to map a run-time instance to a dependency is to use an Abstract Factory.
Instead of registering the individual Strategies with the container, you register the factory.
It is entirely possible to write a complete API so that it's DI-friendly, but still DI Container-agnostic.
If you need to vary the IAlgorithm implementation at run-time, you can change Person to require an algorithm factory that provides different concrete algorithms based on run-time conditions.
Some dependency injection containers let you bind to anonymous creational delegates - if Ninject supports that, you could put the decision logic in one of those.