Because I'm mostly using StructureMap, here's a simple implementation and use case for it. (I'm sure you can implement almost all of the current DI frameworks as easily and similarly as StructureMap.)
public class StructureMapServiceLocator : IMvcServiceLocator
{
protected IContainer Container { get; private set; }
public StructureMapServiceLocator(IContainer container)
{
Container = container;
}
#region IServiceLocator Members
public System.Collections.Generic.IEnumerable<object> GetAllInstances(System.Type serviceType)
{
return Container.GetAllInstances(serviceType).Cast<object>();
}
public System.Collections.Generic.IEnumerable<TService> GetAllInstances<TService>()
{
return Container.GetAllInstances<TService>();
}
...
public TService GetInstance<TService>()
{
return Container.GetInstance<TService>();
}
#endregion
}
The wrapper implementation is pretty straightforward as StructureMap has basically the same methods available.
Using the StructureMap container is as easy as it would be anywhere else, with only one small addition. We have to explicitly say that the ASP.Net MVC controller factory is the DefaultControllerFactory. Just add the following to your Global.asax / Application_Start and you're good to go.
var container = new Container(configuration => {
configuration.For<IControllerFactory>().Use(new DefaultControllerFactory());
});
MvcServiceLocator.SetCurrent(new StructureMapServiceLocator(container));
To add dependencies to your controllers, I've implemented a dummy service:
public interface ISampleService
{
string SayHello(string name);
}
public class ConcreteSampleService : ISampleService
{
public string SayHello(string name)
{
return string.Format("Hello, {0}", name);
}
}
And modified the default HomeController created by the project template:
public class HomeController : Controller
{
protected ISampleService Service { get; private set; }
public HomeController(ISampleService service)
{
Service = service;
}
public ActionResult Index()
{
ViewModel.Message = Service.SayHello("you");
return View();
}
}
Now that we have a dependency in our controller, we can simply configure it with the container (just add it before or after the IControllerFactory registeration):
configuration.For<ISampleService>().Use<ConcreteSampleService>();
That's it. Just run the web site and you should see a nice "Hello, you" message instead of the standard "Welcome to ASP.NET MVC!".

-==- References -==-
You should also check out Brad Wilsons post that also covers view engine and filter injection.
Also, if you haven't already seen what else is new on MVC 3, then ScottGu's post is a must read.
-==- Source -==-
Can be downloaded from here.
0 comments:
Post a Comment