https://msdn.microsoft.com/en-us/library/microsoft.practices.unity.perrequestlifetimemanager(v=pandp.30).aspx states that:
Although the PerRequestLifetimeManager lifetime manager works correctly and can help in working with stateful or thread-unsafe dependencies within the scope of an HTTP request, it is generally not a good idea to use it when it can be avoided, as it can often lead to bad practices or hard to find bugs in the end-user's application code when used incorrectly. It is recommended that the dependencies you register are stateless and if there is a need to share common state between several objects during the lifetime of an HTTP request, then you can have a stateless service that explicitly stores and retrieves this state using the Items collection of the Current object.
What kind of bugs or bad practices is the warning refering to? How would one use it incorrectly? - Unfortunately the warning is not very specific and is therefore hard to apply to the real world. Furthermore it is not clear to me what stateful means in this context.
IMHO a typical scenario to use the PerRequestLifetimeManager would be some kind of database connection (e.g. DbContext) or similiar.
Its purpose would be to only instantiate one instance per request, which could (for example) prevent redundant operations and lookups during the course of a single request.
The danger is if someone assumes that the object created is a good place to store state during the request. The idea of dependency injection is that a class receives a dependency (commonly an interface) and doesn't "know" anything about it at all except that it implements that interface.
But someone could reason that if the object is going to persist throughout the life of the request then it's a good place to maintain state during the request. So they create a complex scenario where one class receives the dependency, stores some information in it (like setting a property), and then another class receives that same dependency and expects to read that property.
Now the purpose of dependency injection (decoupling) has been defeated because classes have built-in assumptions about what the lifetime of that dependency is, and may even include assumptions about what other classes have done or will do with the state of that object. That creates a tangled mess where the interaction between classes is difficult to perceive - even hidden - and so it's easy to break.
Let's say someone determines that the lifestyle of that dependency should be transient, not per web request. Suddenly all of the behaviors of those classes that depend on it stop working as expected. So developers look at those classes and see that nothing has changed. What happened? The interaction between those classes was hard to see in the first place, so when it breaks the problem will be hard to find. And if there was some valid reason why the lifestyle of that dependency was changed then the problem is going to be even harder to fix.
If we need to store state during a request then we should put it in "normal" places like in the HttpContext. There's still room there for some confusing practices and bugs, but at least we know that the HttpContext is (by definition) going to be tied to a particular request.
Related
I have a service that stores the applications state. For this reason I've made it singleton. It's passed into the constructor of some WebAPI controllers to expose some of it's state and functions. A permanent reference is held by a background worker which is continuously doing things and making state changes.
This state service has some persistence in that certain changes result in db writes. These are non blocking but that's besides the point. The single service needs to reference one or more repositories. A repository is just a generic class that has a get and insert method for it's given type. It's passed an IDbConnection into it's constructor. The repositories themselfs are passed into the singleton service constructor.
DI does the build up of the chain and it throws an error due to singleton objects (the service) depending on transient objects (the repositories). I wasn't obvious to me at first but this does make sense and could cause concurrency issues.
https://simpleinjector.readthedocs.org/en/latest/LifestyleMismatches.html
The DI suggestions are make the dependancies singleton, make the owner not singleton or pass in a factory for the depentancies instead. Therein lies my quandary.
We're talking about the interface between singleton and non-singleton and how that is bridged. The service needs to be singleton of the far left of the graph, and the IDbConnecton must be transient on the far right, so a factory is needed to be the bridge but where to put it.
I could inject a factory that creates repositories but that would mean creating a new repository object for each individual repository operation. This seems quite a wasteful thing to do. Admittedly the repository doesn't hold any state, but it does seems logical then to make the repository itself singleton and give it a factory that produces IDbConnections.
The factory could in fact just wrap a connection pool but that's implimentation detail. It feels somehow dirty making a repository singleton to satisfy the dependency chain, even though it does make logic sense when I think it through.
Id appriciate it if anyone could sanity check me. It feels like there is some kind of mistake in my reasoning, or that I'm nibbling around the edges of a pattern that I don't know about.
As I was reading, the factory approach was already in my mind before you had introduced it. For me, the RepositoryFactory seems the most attractive approach as they sound inexpensive to create and can then be given any scoped dependencies they might need. I.e. a connection shared across more than one repository.
I've just started learning about IoC, and I understand the general use of it, but so far, the loading process from AutoFac, Ninject and Zenject seem to be based on loading an object not based on data.
In other words, ConsoleLogger is created when ILogger is requested, which does not require any special ID's, and that makes sense. However, what about when I want to load IUser for Id 4? Is there a standard IoC for handling that, or are the interfaces supposed to carry methods for loading based on Id?
For instance, am I supposed to have IUserManager, with LoadUser(int id) as a method? or is there some IoC structure for this as well?
Thanks.
[note: I did search the web for this, but my queries did not seem to pull up relevant information and the similar question search yields too many generic questions to filter]
IoC containers rules the way we link object's by dependencies, dependencies means some logic under Iterfaces, so IoC mostly works on Type level rather then Instance level.
Please note that types which has no any dependencies, interfaces as well as special scope requirements may be legally created by using "new" keyword for e.g. Data Transfer Objects (dto's).
In your case, you probably need a some kind of factory that can realize by parameters what kind of object caller is needed.
However, I'll suggest to you separate data from business logic as much is it can be separated.
I would like to use a common Autofac module in several different web projects.
One of these projects does not require all the classes registered in my common module (it uses about half of them). My guess was that if a class is registered but never called, it will not be resolved and so it will not use up extra memory.
Is this ok or bad practice ? Thanks
I think that the amount of extra memory consumed by Autofac (or any DI container) is minimal -if- those types are never resolved. Containers have lazy-load mechanism, which prevents slow startups. When a type is resolved for the first time, containers often generate a lot of code and memory in the background to be able to do fast resolves at any later request for that type. Do note though that containers that contain some sort of 'verify' feature often force an instance to be created which will trigger the whole building and compilation process. So if you call this verify feature during startup, you lose the lazy-loading benefits.
Some developers even go a step further and tel the container to go reflect over all assemblies and register any type it finds by its interfaces. When doing this, you might see a lot of types ending up in the container that are never used and can actually never be resolved (because they weren't intended to be created by the container). The idea is that this keeps the container configuration very simple, and they don't care about the extra garbage.
Although this can simplify the container's configuration, downside of this approach is that this makes it much harder to have a simple integration test that verifies the correctness of the DI configuration, because there will be a lot of false-positives; the test will constantly fail because there are a lot of invalid registrations in the container. And it gets even worse if your container contains some sort of diagnostic service that allows detecting common misconfigurations. Again such configuration will trigger lots of false-positives or might even disable this feature altogether (depending on the framework you use).
That's why I usually advice against doing this type of batch-registration (although I'm not against batch registration itself).
Performance wise probably not, but...
...this means that you also have to add unneeded references to your project. I would avoid it to keep the amount of dependencies as low as possible. According to me, registering dependencies is something that belongs to your application, and not something that is shared across multiple applications. After all, things like life time may vary depending on the application.
I'm a newbie to Dependency Injection. I have never used and never even undestood what it is exatcly all about, but after my last attack on this topic I found out that is a way of uncoupling an object and its dependencies, once they are not responsible for instantiating the concrete versions of its dependencies anymore, as now the container will do it for us and deliver the ready object in our hands.
Now the point is; "when should I use it?", ALWAYS??? Actually, as I'm a newbie and have never even seen a project that uses this pattern I can't undestand how I should apply it to my domain objects!!! It seems to me that I will nevermore instantiate my objects and the container will always do it for me, but then comes some doubts...
1) What about oobjects that part of its dependencies comes from the UI, for example;
public class User(String name, IValidator validator)
Say that I get the user name from the UI, so how will the conatiner know it and still delliver this object for me?
2) Theres other situation I'm facing; if a dependency is now an object that is already instantiated, say... a SINGLETON object, for example . I saw theres settings regarding out the scope of life of the dependency beign injected (im talking about Spring.NET, eg; http request scope)... BUT, request and other web related things are on my presentation layer, so how could I link both my presentation layer and my domain layer without breaking any design rule (as my domain should be totally unaware of where its is being consumed, not to have layer dependency, etc)
Im eager to hear from you all. Thanks very much.
In general, once you go IoC, you tend to want to register EVERYTHING with IoC and have the container spit out fully-hydrated objects. However, you bring up some valid points.
Perhaps a definition of "dependency" is in order; at its broadest, a dependency is simply a set of functionality (interface) that a given class requires a concrete implementation of in order for the class to work correctly. Thus, most non-trivial programs are full of dependencies. To promote ease of maintenance, loose coupling of all dependencies is generally preferred. However, even when loosely coupled, you don't need to automate instantiation of dependencies if those objects require specialized information that you don't want to pollute your IoC registry with. The goal is to loosely couple usage, not necessarily creation.
Concerning point 1, some IoC frameworks don't do well with being given external parameters. However, you can usually register a delegate as a factory method. That delegate may belong to an object like a Controller that is given external information by the UI. Logins are a perfect example: Create an object, say a LoginController, and register it with IoC as your ILoginController. You'll reference that controller on your Login page, it will be injected when the Login page is instantiated, and the login page will pass it the credentials entered. The Controller will then perform authentication, and will have a method GetAuthenticatedUser() that produces a User object. You can register this method with IoC as a Factory for Users, and whenever a User is needed, the factory delegate will either be evaluated, or passed wholesale to the dependent method which will call it when it really needs the User.
On point 2, setting up a single instance of an object is a strength of the IoC pattern. Instead of creating a true singleton, with a private instance constructor, static instance and static constructor to produce an instance, you simply register the class with IoC and tell it to only instantiate it once and use that one instance for all requests. The strength is the flexibility; if you later want there to be more than one instance, you just change the registration. You won't break any design pattern rules either way; the view will always have a Controller injected, whether that Controller is the same for all pages or a new instance per request.
1) this contructor is probably not the right one to use, may be you are injecting the validator in the wrong place/way.
2)Neighter View nor Model and nor Controller should be aware of there is an IoC, it should lie in the background architecture ( where MVC components are actually instantiated )
You should use IoC when you feel the architecture can became complex and has to be mantained by many people. If you are writing an enterprise application, or a UI you think to extend with plugins, you probably need it, if you are writing a command line utility, probably not.
You should use dependency injection whenever you want any of the following benefits:
The ability to replace modules easily
The ability to reuse modules between parts of the application, or different applications
When you want to do parallel development, so that components of a system can be developed in isolation and in parallel because they depend on abstractions
When you want easier maintenance of a system because of loose coupling
When you want testability (a specialisation of replacing modules). This is one of the biggest reasons for using DI
To answer your other questions:
1) You can configure many IoC containers so that certain constructor parameters can be specified, whilst others are resolved by the container. However, you may need to think about refactoring that piece of code, as a UserFactory may be more appropriate which takes the validator dependency, and has a NewUser method which takes a user name and returns a new user (either instantiating it directly or resolving from the container).
2) Each application you build will have a composition root, where your container is configured, and the root object is resolved. Each app will therefore have its own IoC configuration, so there is an expected link between the application type and the configuration settings. Any common abstraction registrations can be placed in configuration code which can be shared amongst all applications.
More specifically, What's the best approach for classes where state matters, within an application which implements Dependency Injection.
Say I need access to an object that's in a particular state. For example, this object might have been initiated in a different thread, or by a process I have no control over.
A good example of an object like this that already exists in .NET is the HttpContext.
In this case, Microsoft decided to go with the Static approach, so I just say:
var currentObj = HttpContext.Current;
And this gives me a particular instance of an object without having to worry where it came from.
The problem with the Static approach is that it doesn't play very nicely with dependency injection.
The other option is to configure your certain class as a Singleton in your IoC Container. This means that you can inject it, and depending on the current IoC Container config it'll be the correct instance of the class.
However, the downfall of this approach is that the stateful importance of the object is no longer explicit in the code, it's not obvious by looking at it. With the Static class used to access and instance it's more clear that the state is important. Maybe that doesn't matter though.
So, is there a pattern that helps me out here?
Context:
For context, I'm working on an application which has many instances of a class performing IO operations. They exists within their own threads.
I want to be able to interact with those objects (background tasks) via a web interface, so a Controller. I want to be able to interrogate them, and manipulate them etc.
Update:
Sorry, I think my use of the term "stateful" is a bit misleading. let me explain some thing:
"state" is probably the wrong word. I mean communicating with an object whereby I don't have control over it's lifecycle.
It is funny that I use "stateful" when talking about static classes. That's why I gave the HttpContext example, as that exactly what it does. The Current property gets you a very specific instance, not any new instance.
When I say that static doesn't play nice with DI, I meant, you can't inject Static classes. I could create a wrapper, yes, but I'm just pushing the problem elsewhere no?
I should have been more clear about my definition of Singleton. I meant a Singleton lifestyle, as defined in an IoC Container.
I always prefer Singleton over static. In fact, I almost never use statics in my own classes.
True singletons and static classes are both very difficult to write automated tests against. Do you mean a single instance looked up at runtime? That would make sense to me but I don't know the right construct to use in C#. The analog in Java is JNDI.
Neither or both. Presuming the stateful dependency is thread-safe the better approach is to build at least a basic layer of abstraction around said dependency then inject said abstraction into your classes. Singleton vs static becomes pretty immaterial then.