Is Dependency Injection a must in asp.net MVC? - 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.

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.

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.

What are the next steps for unit testing with dependency injection?

I'll start out by saying I'm a huge fan of unit testing. I've been using it for a couple of years. So far, though, my use has been limited to ensuring engineering calculations are performed correctly, strings are formatted properly, etc. Basically, testing my work on class libraries to be consumed in other projects.
Now, I want to branch out and apply unit testing to my work on ASP.NET Web API. At this point I have my controller written and working with Ninject. Although I'm using Ninject, I'm still not 100% sure why I'm doing it and haven't seen the benefits yet.
On to my question, what are the next steps for unit testing my Web API controllers? What should I do next and when will I reap the benefit of using Ninject?
Next, you could create fake data (or a mock) that your controller can return to your views. This will allow you to do front end development without having to complete the back end implementation.
The benefit of using Ninject is that you can create mock objects for testing purposes. By injecting the interface instead of the concrete implementation you can easily switch between the real and mock object. To do this you simply change which one should be injected in the Ninject bindings. Using something like Rhino Mock in conjunction with Ninject you can write and test your code (controllers, views, etc) without having to fully implement all of the functionality. When you're ready to implement a mocked piece of functionality, you don't have to rewrite your code to accommodate the changes, you simply update your bindings. Now real data will display on your pages instead of the mocked data you created previously.

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.

Resources