Should (and if so how should) a database context be dependency injected into a controller? - asp.net-mvc-3

It seems like at least 90+% of the Controller Actions I am writing will need to access the database. To me it seems like a logical step to have the database context automatically injected.
I have never used dependency injection before so I want to confirm this is something that is a pattern. If it is, how should I go about doing this? I know ASP.NET MVC 3 has "improved dependency injection" support, but do I still need an external framework? If so what is the default and how do I configure it to create a new database context per http request?

ASP.NET MVC 3 doesn't have improved DI support - it has improved support for the Service Locator anti-pattern (go figure). Fortunately it has had support for DI since MVC 1 through the IControllerFactory interface.
To answer the question, however, yes, it sounds like a perfectly normal thing to inject a Repository into a Controller (although normally we would slide a Domain Model in between the two).
This is best done with Constructor Injection like this:
public class MyController
{
private readonly IMyRepository repository;
public MyController(IMyRepository repository)
{
if (repository == null)
{
throw new ArgumentNullException("repository");
}
this.repository = repository;
}
public ViewResult MyAction(int barId)
{
var bar = this.repository.SelectBar(barId);
return this.View(bar);
}
}
You'll need to provide a custom IControllerFactory to enable Constructor Injection with the MVC framework - the easiest thing is to derive from DefaultControllerFactory.
Once you have a custom IControllerFactory, you can register it in Global.asax like this:
ControllerBuilder.Current.SetControllerFactory(new MyControllerFactory());

Related

WebAPI: Accessing Child Container as a Service Locator

In normal ASP.MVC projects we configure the dependency resolver with Unity and the Unity.Mvc3 package from http://unitymvc3.codeplex.com/
We have this test service registered with a HierarchicalLifetimeManager
container.RegisterType<ITestService, TestService>(new HierarchicalLifetimeManager());
And we hook up the container with Mvc in Global.asax.cs:
System.Web.Mvc.DependencyResolver.SetResolver(new Unity.Mvc3.UnityDependencyResolver(container));
And we run this test controller:
public class TestController : Controller
{
private readonly ITestService _service;
public TestController(ITestService service)
{
this._service = service;
}
public ActionResult Test()
{
var locatedService = System.Web.Mvc.DependencyResolver.Current.GetService<ITestService>();
if (_service == locatedService)
return View("Success - Same Service");//This is always the result in an MVC controller
else
throw new Exception("Failure - Different Service Located");//This is never the result in an MVC controller
}
}
However, on this project we are adding a number of WebAPI controllers.
We have this configuration in global.asax.cs (using http://unitywebapi.codeplex.com/ for now. But I am open to suggestions):
System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);
We have created an ApiTestController similar to TestController inheriting from ApiController rather than from Controller.
However, the ApiTestController fails its test. I understand that the System.Web.Mvc.DependencyResolver class and the System.Web.Mvc.DependencyResolver.Current property are specific to Mvc. But does WebAPI have an equivalent?
System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver.GetService does not work because the System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver instance is the parent container that I configured. It is not the child controller that was used to inject the ITestService into the constructor.
This user seems to have a similar problem: http://unitywebapi.codeplex.com/discussions/359413
But I feel that this probably has more to do with ASP.NET's WebAPI than it has to do with Unity.
Thanks
After looking over the source of http://unitymvc3.codeplex.com/ and http://unitywebapi.codeplex.com/ I created this class:
public class MyUnityDependencyResolver : Unity.Mvc3.UnityDependencyResolver, System.Web.Http.Dependencies.IDependencyResolver
{
public MyUnityDependencyResolver(IUnityContainer container)
: base(container)
{
}
public System.Web.Http.Dependencies.IDependencyScope BeginScope()
{
return this;
}
public void Dispose()
{
Unity.Mvc3.UnityDependencyResolver.DisposeOfChildContainer();
}
}
Configuration in gobal.asax.cs:
var myResolver = new MyUnityDependencyResolver(container);
System.Web.Mvc.DependencyResolver.SetResolver(myResolver);
System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver = myResolver;
Unity.Mvc3.UnityDependencyResolver uses HttpContext.Current.Items to manage child containers. MyUnityDependencyResolver may not be the most "correct" implementation of System.Web.Http.Dependencies.IDependencyResolver, but it seems to work so far.
I will mark this as the answer in a couple days if no one else has any better answers.
Unfortunately, when you call the GlobalConfiguration.Configuration.DependencyResolver.GetService, it completely ignores any scope and resolves using the outer non-child container which is around for the lifetime of the application. This is an issue with Web Api and makes it impossible to use constructor injection for per-request dependencies outside of controllers. Confusingly this is completely different behaviour from MVC as you say.
What you can do is use the GetDependencyScope() extension method off HttpRequestMessage. Anything you resolve using this will be in per request scope when using HierarchicalLifetimeManager in conjunction with Unity.WebApi. The request is available from action filters and handlers so may be a viable workaround.
Obviously this is pure service location rather than dependency injection which is far from ideal but I have not found another way to access per-request dependencies outside of controllers.
See this post for more info.
The DependencyResolver is not the right seam for dependency injection in ASP.NET WebAPI.
Mark Seemann has two really good posts on DI with WebAPI.
Dependency Injection and Lifetime Management with ASP.NET Web API
Dependency Injection in ASP.NET Web API with Castle Windsor
If you want to do it right you should have a look at them.

Architecture and Microsoft.AspNet.Providers

I have been Googling for hours and cant find an article that is exactly related to what I need.
I have a MVC4 site with the following layers:
Presentation layer (MVC4)
Business Layer
Data layer
I want to use the following provider:(installed using NuGet)
Install-Package Microsoft.AspNet.Providers
My question is more of an architectural one.
In my mind, I should install this (Microsoft.AspNet.Providers) in my data layer as it is code that talks to a membership database.
All the posts I can find, however, even by Hanselman just install it in the Presentation layer / MVC4.
I am very big on separation of concerns and am using dependency injection throughout my application.
Obviously I need the config for the provider in my web.config but want all the membership code in my data layer.
Any thoughts?
thanks
RuSs
PS. Would love to know the process of installing this in a data / repository layer using nuget. Slightly confused as to what DLLs Nuget is installing. If I install in my data layer, nuget doesnt update the MVC web.config.
The answer is quite simple actually: You should hide the providers behind an abstraction that you define in your business layer. This way you can write an adapter that implements this abstraction an wraps the provider and you can inject this adapter into your business layer using dependency injection. This way you will only have to reference the Microsoft.AspNet.Providers from your MVC4 project, and prevent any code from directly referencing the AspNet.Providers, which allows you to switch more easily later on.
Example:
// Define in business layer
public interface IAuthorizationService
{
bool bool IsCurrentUserInRole(string role);
}
public class SomeBusinessLayerCommand
{
private IAuthorizationService authorizer;
public SomeBusinessLayerCommand(
IAuthorizationService authorizer)
{
this.authorizer = authorizer;
}
public void SomeOperation()
{
if (this.authorizer.UserIsInRole("Admins"))
{
// some secret admin stuf
}
else
{
// some normal user stuf
}
}
}
And in your Presentation Layer you can define an adapter:
public class MembershipAdapter : IAuthorizationService
{
public bool IsCurrentUserInRole(string role)
{
return Roles.IsUserInRole(role);
}
}
And you can map IAuthorizationService to MembershipAdapter using your favorite DI container.

When Using the Service Layer Pattern, Is there a Folder Layout Convention for a Visual Studio 2010 Solution?

I want to use the Service Layer patter (as described on Martin Fowler's site here) for my ASP.NET MVC 3 application.
My goal is to setup the solution structure in a way for me to more easily learn the pattern by setting up the proper framework for it prior to digging into the code.
Can anyone show me the conventional way to layout the solution, projects, and folders within a Visual Studio 2010 Solution?
There are many ways to implement this. Either segment the service layer into a separate assembly or it could be in the same assembly as the ASP.NET MVC application (for example in a Services folder). There is really no rule for that. It will depend on the level of reusability you are expecting from this layer and the size of your project. What is important though is to abstract this service layer:
public interface IMyService
{
... some service methods
}
and then have your controllers work only with this abstraction:
public class MyController: Controller
{
private readonly IMyService _service;
public MyController(IMyService service)
{
_service = service;
}
public ActionResult MyAction()
{
... call some methods on the service layer
}
}
Then to wire up the concrete implementation you would configure your dependency injection framework.

MVC 3 And MEF and adding plug-ins to main application

I am a newbie to MEF and I am really mixed up! There are lot of useful articles out there and neat question and answers here in stackoverflow. I downloaded the example which #matthew-abbott has uploaded in his blog , but I dont know how to add new plug-ins or extension to extend the main web application, I mean like what you can see here.
Edited :
Also I use Entity Framework, Code First Approach and Unit of work for my data access layer application, what If my plug-ins needs data access and (I mean the plug-in has itself models) wants to use the DAL I created ? As you know every time the model changes, DbContext throws and error and tells re-create DB, Is there any way or other ORM which accepts extending DAL dynamically?
That particular example shows how we can integrate MEF with MVC3's new DependencyResolver which provides a service location mechanism for various extension points within the MVC architecture. There are a few other articles on my blog which detail more information about how a possible plugin architecture could work, these are available at:
Modular ASP.NET MVC using the Managed Extensibility Framework (MEF), Part One
Modular ASP.NET MVC using the Managed Extensibility Framework (MEF), Part Two
Modular ASP.NET MVC using the Managed Extensibility Framework (MEF), Part Three
There are also a host of fantastic articles, my recommendations would be to also read:
ASP.NET MVC and the Managed Extensibility Framework (MEF) by Maarten Balliauw
Defining Web-scoped parts with MEF by Tim Roberts
MVC is a very flexible architecture, there are a myriad of ways it can be extended, but because of the nature of how ASP.NET applications run in IIS, you need to consider part lifetime very carefully. As an example, controllers can only be used for one request, so you could would need to ensure that your controllers have a specific CreationPolicy. Tim Robert's article on Web-scoped parts is a particularly good read.
Hope that is enough to point you in the right direction.
Edit: Because of the modular nature that MEF provides, it is important to ensure that your different layers are decoupled. You've specified that you are using Entity Framework, but the reality is, EF should likely only be used in your data layer. Typically the MVC architecture would promote view models over domain models. To that end, it is probably useful to use something similar to the repository pattern to define, e.g. here is a mock UserRepository:
[Export(typeof(IUserRepository))]
public class UserRepository : IUserRepository
{
public IEnumerable<UserViewModel> GetUsers()
{
// Get values here from EF as domain models
// And return them as view models?
}
}
Which we can export and inject into a controller:
[ExportController("User"), PartCreationPolicy(CreationPolicy.NonShared)]
public class UserController : Controller
{
private readonly IUserRepository _repo;
[ImportingConstructor]
public UserController(IUserRepository repo)
{
if (repo == null)
throw new ArgumentNullException("repo");
_repo = repo;
}
public ActionResult Index()
{
var users = _repo.GetUsers();
return View(users);
}
}
This is just a really simple example, but like many IoC containers, MEF also supports dependency injection. As long as a part provides a suitable export, it can be imported (either through property injection, or constructor injection) into another part at composition time.
My recommendation would be against exposing EF to your views, as this makes them explicitly dependent on it. By taking care to decouple and only expose the right types at the right layers, you architecture will become a lot more robust, flexible and testable, which makes maintaining it, and updating it a lot easier. As another quick example, here is how we could test our controller:
[Test]
public void UserController_CreatesViewResult_WithListOfUsers()
{
var mock = new Mock<IUserRepository>();
mock.Setup(m => m.GetUsers()).Returns(new[] { new UserViewModel { Name = "Matt" } });
var controller = new UserController(mock.Object);
var result = controller.Index();
Assert.That(result is ViewResult);
// Other assertions.
}
Because I haven't tightly coupled EF to my view, my controller is a lot more testable, I can mock a suitable repository and test where I need to.
The important thing is planning your architecture.

ASP.NET MVC Views Dependency Injection without DependencyResolver?

Is it possible to inject dependencies into an MVC ViewPage (must support layout pages) without using DependencyResolver?
I would rather not use DependencyResolver at all (I had major problems when injecting NH sessions into ActionFilters in the past (leaking all over the place)). However, I'm not sure if there is an alternative?
The other complexity I have is that the DependencyResolver needs to be tenant aware (each tenant has its own (StructureMap) container). I'm currently doing this by passing in a lazy instance of my tenant container resolver (seems this is necessary otherwise the resolver is cached):
public SmDependencyResolver(Func<ISiteContainerResolver> containerResolver)
{
this.containerResolver = containerResolver;
}
public object GetService(Type serviceType)
{
var container = containerResolver().Resolve();
If I end up using DependencyResolver should I ditch my StructureMap controller factory since it looks like DependencyResolver handles this too?
Thanks
Ben
Given that the DependencyResolver is used by so many aspects of the ASP.NET MVC framework for dependency injection your life will be easier if you use it - as you say it means you don't need your own versions of things like the controller factory.
That said, the framework is very flexible and it is always open for you to plug in your own version of things - I just prefer to create as little of my own code as possible on the KISS principle.

Resources