Can Dependency Injection delay creating objects required? - asp.net-mvc

I'm playing around with some Dependency Injection (StructureMap) with my ASP.NET MVC application. Works great.
Becuase StructureMap is using DI via the most gready constructor (I hope I got that concept named right), I'm under the impression that it creates an instance of an object for each argument, in the most gready constructor.
So, is it possible to tell a DI framework (in this case, it's StructureMap but i'm curious if it can do it for any other .NET DI Framework) to NOT create the instance when the constructor is called, but to delay that object's construction until required?
Sorta like some lazy-object construction or something...

All di frameworks that support singleton->session/request scoped mappings typically instantiate a proxy object instead of the "real" object when a singleton object needs to access a session scoped object. Construction of the "real" instance is normally deferred to the first time a method on the proxy is invoked.
I believe castle windsor supports this mechanism.

Short answer: Yes, you can do this. Register your types using the .Net 4 Lazy<T> class like this:
x.For(typeof(Lazy<>)).Use(typeof(Lazy<>))
.CtorDependency<bool>("isThreadSafe").Is(true);
For the long answer and explanation, see my answer to question 6811956. I think it will give you what you need. If you aren't using .Net 4 you'll have to implement your own Lazy<T> class to pull this off. See question 3207580 as a starting point.
Does Structuremap support Lazy out of the box?
Implementation of Lazy<T> for .NET 3.5
UPDATE: In StructureMap 3, "CtorDependency" has become just "Ctor", but otherwise seems to be working just the same.

Related

Dependency Injection in .net core, Autofac vs StructureMap vs Factory Method to resolve interface if registered with multiple implementation

In my project I using chain of responsibility designing pattern for which I need to create multiple handlers which will implement same interface. In .net application(not .net core) I would have used DI using UnityContainer where I could have resolved handlers using named parameter. But in .net core I can not do that. Now I have few options to use other DI libraries like Autofac, Structuremap or create factory method which can give me objects based on name passed. Please help me in picking right approach between these or suggest something better if available. I have not used Autofac or Structuremap so I very little idea of same. Thanks.
For the most part, all DI tools out there achieve the same thing with different APIs. These days the differences are highlighted by your needs.
StructureMap or Autofac are both good candidates. It all boils down to "flavor".
Check this article. I think is a good one. Configuration comparison dependency injection containers
Again, don't stress over them unless you need a very very specific feature form one of them.
I would do Autofac just because I haven't had the need for something else however, I would not hesitate to use StructureMap, Ninject or whatever new kid on the block is brought up.

Does Microsoft DependencyInjection support non-constructor injection?

I am trying to incorporate Microsoft.Extensions.DependencyInjection into an existing ASP.NET 4.6.1 app.
I know that while .NET Core has it built-in, for 4.6.1 you need to create some initial classes as outlined in http://scottdorman.github.io/2016/03/17/integrating-asp.net-core-dependency-injection-in-mvc-4/. (The article seems to be out of date since the sample code does not show implementation of BeginScope() and Dispose() for IDependencyResolver. If anybody has more updated examples that would be appreciated.)
"Services" accessed by controllers where you are creating instances via constructors is fairly simple but my problem is when I need an instance of "something" that is from a property or method of an existing object.
For example, I have a inherited DbContext that needs an instance of System.Security.Principal.IIdentity that comes from the logged in user.
Another example is an instance of ApplicationUser. ApplicationUser inherits IdentityUser and the current user can be found by calling FindById() method of AppUserManager.
While AppUserManager can easily be instantiated using DI, how can I use DI the inject the output of the FindById() method? I cannot seem to find any documentation or sample code about this for Microsoft based framework. Other frameworks like Unity seem to support Property-based injection.
In essence, can DI be used with all existing classes or do you specifically need to code out the classes to support DI from the beginning? (i.e. only expect parameters to be passed in via constructors and make sure those instances themselves are created via constructors).
The very simple and short answer to your question "Does Microsoft DependencyInjection support non-constructor injection?" is, no.
Out-the-box Microsoft DI does not currently support property injection like other frameworks such as Ninject. If you need that feature, I suggest using those frameworks instead (I cant imagine MS has any plans to add property injection any time soon).
Your other option is to consider how you can refactor your code to use constructor injection instead which is the preferred method

Is it a good idea to pass the data context object to controllers with dependency injection?

I am currently using the CustomControllerFactory object to pass services (which each implement an interface) to my controllers.
I am wondering whether it is a good idea to do the same for my data context objects.
Currently at the top of each of my controllers, I have the line:
private dataContextClass db = new dataContextClass();
I have created an interface that dataContextClass implements. I can only see examples online of people passing services in with dependency injection. Is it a good idea to pass the data context object in as well?
Of course it's a good idea. The context is a dependency of your controller, and therefore should be injected if you're using dependency injection. However, you didn't specify what version of MVC you're using, but custom controller factories were deprecated in MVC 3. If you're using that version or later, you should be handling injection via IDependencyResolver. And, in general, it's usually better to just use a full-fledged DI container like Unity or Ninject, than to try to create your own from scratch.

Autofac Container Independence and Relationship Types

We are currently using Autofac as our chosen IoC container. All application code in our reusable assemblies must be kept as clean as possible, so we do not want any direct dependencies on Autofac in our core application. The only place where Autofac is permitted is in the composition root / bootstrappers, where components are registered and wired up. Applications rely on dependency injection to create the required object graphs.
As we are keeping our core application container agnostic, it means that we cannot use the Autofac relationship types, such as Owned, in our core application.
I would like to create a factory that returns components that implement IDisposable. As Autofac tracks disposable objects, I believe I have to use a lifetime scope to create a defined unit of work in which components will be disposed once they go out of scope.
According to the Autofac documentation, this can be achieved by taking a dependency on Func<Owned<T>>, however, as stated above, I cannot take a dependency on Owned as it is an Autofac type. At the bottom of this page, it says
The custom relationship types in Autofac don’t force you to bind your application more tightly to Autofac. They give you a programming model for container configuration that is consistent with the way you write other components (vs. having to know a lot of specific container extension points and APIs that also potentially centralise your configuration.)
For example, you can still create a custom ITaskFactory in your core model, but provide an AutofacTaskFactory implementation based on Func<Owned<T>> if that is desirable.
It is this implementation of ITaskFactory that I believe I need to implement, but I cannot find any examples.
I would be very grateful if someone could provide such an example.
Probably the best "real-world" example of this is the Autofac MVC integration mechanism. While it doesn't use Func<Owned<T>> under the covers it does show you how you might be able to implement a non-Autofac-specific mechanism to talk to Autofac under the covers.
In the MVC case, the System.Web.Mvc.IDependencyResolver is the interface and the Autofac.Integration.Mvc.AutofacDependencyResolver is the implementation. When ASP.NET MVC requests a service, it gets it from System.Web.Mvc.DependencyResolver.Current, which returns an IDependencyResolver. At app startup, that singleton gets set to the Autofac implementation.
The same principle could hold for your custom factory. While IDependencyResolver is not specific to the type it returns (it's just GetService<T>()) you could write a type-specific factory interface just as easily.

WebApi controller dependencies cannot be resolved using StructureMap

I'm currently using StructureMap with MVC, but its complaining that my api controllers don't have a default constructor. Can someone point me in the right direction in order to set this up with StructureMap? As I understand, MVC and WebApi have separate resolvers (which makes sense since they are separate frameworks).
I have done it for AutoFac here. Should give you enough pointers to implement it yourself.

Resources