如果你正在使用MVC 3,要正确地做事情,你应该使用内置的依赖分辨率位。我强烈建议你阅读series of blog posts from Brad Wilson(ASP.NET MVC团队的成员)。
就StructureMap特定实现而言,我发现以下博客文章很有帮助。
StructureMap and ASP.NET MVC 3 – Getting Started
StructureMap, Model Binders and Dependency Injection in ASP.NET MVC 3
StructureMap, Action Filters and Dependency Injection in ASP.NET MVC 3
StructureMap, Global Action Filters and Dependency Injection in ASP.NET MVC 3
总之,这里的一些代码。首先,我建议你安装StructureMap-MVC3 NuGet package。
我不记得它以文件的方式创建了什么,但这里是基本涉及的内容。
/App_Start/StructuremapMvc.cs - 此挂钩插入的Application_Start并建立您的容器(SmIoC.Initialize()
),然后设置MVC 3 DependencyResolver到您的SmDependencyResolver
using System.Web.Mvc;
using YourAppNamespace.Website.IoC;
using StructureMap;
[assembly: WebActivator.PreApplicationStartMethod(typeof(YourAppNamespace.App_Start.StructuremapMvc), "Start")]
namespace YourAppNamespace.Website.App_Start {
public static class StructuremapMvc {
public static void Start() {
var container = SmIoC.Initialize();
DependencyResolver.SetResolver(new SmDependencyResolver(container));
}
}
}
/IOC/SmDependencyResolver。 cs - 这是您的MVC 3 IDependencyResolver实现。它在上面的App_Start代码中使用。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using StructureMap;
namespace YourAppNamespace.Website.IoC
{
public class SmDependencyResolver : IDependencyResolver
{
private readonly IContainer _container;
public SmDependencyResolver(IContainer container)
{
_container = container;
}
public object GetService(Type serviceType)
{
if (serviceType == null)
{
return null;
}
try
{
return _container.GetInstance(serviceType);
}
catch
{
return null;
}
}
public IEnumerable<object> GetServices(Type serviceType)
{
return _container.GetAllInstances(serviceType).Cast<object>(); ;
}
}
}
/IoC/SmIoC.cs - 这就是你设置你的容器......在App_Start代码也可使用。
namespace YourAppNamespace.Website.IoC
{
public static class SmIoC
{
public static IContainer Initialize()
{
ObjectFactory.Initialize(x =>
{
x.For<IProjectRepository>().Use<ProjectRepository>();
//etc...
});
return ObjectFactory.Container;
}
}
}
现在一切都被迷住了......(我想;-)但是你还有最后一件事情要做。在你的Global.asax
里面,我们需要确保你处理所有的HttpContext作用域。
protected void Application_EndRequest()
{
ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects();
}
所以你应该能够通过构造器注入实现依赖注入,这是正确的方式去做事情。
您运行的是哪个版本的MVC? – Charlino
ASP.net MVC 3。 。 – Dismissile
如果您使用的是ASP。NET MVC 3,你应该真正利用它的内置'DependencyResolver'。查看我的答案获取更多信息。 – Charlino