WebApi controller dependencies cannot be resolved using StructureMap - dependency-injection

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.

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.

Dependecy Injection with MVC other than controllers

I am trying to understand dependency injection in MVC. I got some idea and implemented successfully with Controllers using extending DefaultControllerFactory and using ninject. But i read something like DI in views , Actions etc.
I didn't get DI in Views or my understanding is wrong. If yes, please tell me use and how to do that. I didn't understand other DI areas in MVC. Please explain the areas where DI is used in MVC other than Controllers
In MVC, you should try and make your Views as independent as possible. Ideally, the only dependency it rely on is the ViewModel (other view services and helpers are available through the WebPageBase class that all views inherit by default).

Is Dependency Injection a must in asp.net MVC?

I am currently viewing multiple tutorials (and reading books) to start working with ASP.NET MVC.
I see that ninject (or similar) is widely used to implement Dependency injection and from what i understood the main issue here is resource allocation from the classes i need.
We want to be sure for example that we have only one instance of the repo object.
I need to learn first things first so i am interested in knowing how i would create an ASP.NET MVC without using DI techniques and still be correct as far as my object resources are concerned
More info:
I have made some winforms applications. These apps where using a Business Layer DLL (BLL). This BLL had access to my DAL DLL (plain ADO.NET). they are working quite well..
No i want to use the SAME BLL to MVC apps.
With injection or not?
Without injection implementation?
Do i just create the BLL object in my controller constructor and that's all?
ASP.NET MVC doesn't require you to use dependency injection at all. It will work perfectly fine if all of your controllers have default constructors. On the other hand, you will be responsible for creating the objects and managing their lifetimes. If you need to have one repository object for the application, you have to manually implement its lifecycle(using a static variable or Singleton pattern).
If you care about testing, using dependency injection will certainly help you to design more testable and reusable objects. You can easily replace the dependencies with test doubles in your test code and let DI container inject the real implementations in the runtime.
If you are sure about not using it, then make sure all of your controllers have default constructors. You don't need any configuration.
Dependency Injection is not a requirement for using ASP.net MVC. You can definitely build an MVC app without it.
Where it will come in handy is if you want to perform unit testing on your application. If you would like to unit test an action in a controller, if you have DI set up, then you can mock your dependencies that are included in the controller constructor (that DI takes care of when the app is running) and set up responses to return when they are called by the Action.
This is much harder and impractical (if not impossible) to do if you are not using Dependency Injection. In such a case, if you want to use Unit Testing, it will be very hard to write pure unit tests of your Actions, since you will have no easy way to mock your service and data access layers for your tests.
And as you wrote, the DI layer will also enable you to ensure things like having only one instance of the repository objects that you are injecting, etc.

How do I use dependency injection with an ASP.NET MVC model?

I would like to inject a dependency into an ASP.NET MVC model, but I can't figure out where in the pipeline to do the injection.
It's very straightforward with a ControllerFactory, but not nearly as much when dealing with models.
You can find a reasonable How-To on Shiju Vargheses Blog: ASP.NET MVC Tip: Dependency Injection with Unity Application Block
usually i inject dependencies in the controller like this
PersonController(IPersonRepository r)
{
\\ constrtuctor code
}
in the models probably when need some instance of something that inherits an interface you do something like this :
var r = container.Resolve<IPersonRepository>();
I ended up creating a service locator: http://martinfowler.com/articles/injection.html#UsingAServiceLocator
I find it easier than dealing with an IoC container and trying to insert my DI code all over the MVC pipeline.
I'd recommend reviewing S#arp Architecture
http://www.sharparchitecture.net/
Open source framework addon for asp.net mvc.
Are you completely sure you need to inject a dependency into your domain model itself? An entity or business object will typically encapsulate the state and expose methods to modify that state according to business rules. Code that does not fall into this category typically will be found in a service. Have you read into the concept of a domain service at all? Perhaps using one would better suit your needs and you won't need to inject any dependencies into your domain itself.
Checkout this sample I've created based on Ayende's explanations on his blog. Basically, I use Castle as my IoC container and I use Mvc Contrib to add all controllers to the container and make Mvc get them from it. Then I can inject anything into the containers, such as NHibernate ISession.
If you want to inject stuff inside your model classes (entities), NH now supports Dependency Injection of Hibernate-managed objects. See this, this, and this for specific examples for Spring and Windsor.
What your talking about is more along the lines of the Active Record pattern.
Whether AR is possible or not will depend on which ORM/DAO your using.
The AR pattern is generally better suited for small projects.

Can Dependency Injection delay creating objects required?

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.

Resources