Rob*_*est 4 structuremap dependency-injection asp.net-mvc-3
我正在将一个Web应用程序从ASP.NET 3 Preview 1升级到RTM,我对更新的依赖注入方法感到困惑.我正在使用StructureMap,但这与我的问题无关.以前我需要做的就是如下:
x.For<IControllerFactory>().Use<DefaultControllerFactory>();
x.For<IServiceLocator>().Use(MvcServiceLocator.Current);
Run Code Online (Sandbox Code Playgroud)
现在看来我需要提供IControllerActivator,IViewPageActivator和ModelMetadataProvider的实现,因为否则我从StructureMap收到错误,因为MVC尝试使用依赖项解析器来定位它们.从MVC源看,似乎没有公共默认实现.我在设置这些内容时遗漏了什么?当然这些应该按惯例配置?
需要配置什么以及如何使用StructureMap的例子.作为参考,我目前使用以下丑陋的kludge迫使MVC使用其内部默认值:
x.For<IControllerFactory>().Use<DefaultControllerFactory>();
x.For<IDependencyResolver>().Use(() => DependencyResolver.Current);
x.For<IControllerActivator>().Use(() => null);
x.For<IViewPageActivator>().Use(() => null);
x.For<ModelMetadataProvider>().Use(ModelMetadataProviders.Current);
Run Code Online (Sandbox Code Playgroud)
编辑:为了清楚我有一个工作的依赖性解析器的StructureMap实现 - 问题是为什么MVC抱怨所有这些接口没有在容器中配置.
小智 8
通过创建依赖性解析器(IDependencyResolver)类,然后在global.asax中注册该类,我能够使StructureMap与ASP.NET MVC3一起工作.我还没有完全测试这段代码.但是,它在两个应用程序中一直没有任何问题.
StructureMapDependencyResolver.cs
using System.Linq;
using System.Web.Mvc;
using StructureMap;
namespace SomeNameSpace
{
public class StructureMapDependencyResolver : IDependencyResolver
{
private readonly IContainer container;
public StructureMapDependencyResolver(IContainer container)
{
this.container = container;
}
public object GetService(System.Type serviceType)
{
try
{
return this.container.GetInstance(serviceType);
}
catch
{
return null;
}
}
public System.Collections.Generic.IEnumerable<object> GetServices(System.Type serviceType)
{
return this.container.GetAllInstances<object>()
.Where(s => s.GetType() == serviceType);
}
}
}
Run Code Online (Sandbox Code Playgroud)
的Global.asax.cs
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
DependencyResolver.SetResolver(new StructureMapDependencyResolver(InitContainer()));
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
private static IContainer InitContainer()
{
ObjectFactory.Initialize(x =>
{
x.Scan(y =>
{
y.WithDefaultConventions();
y.AssembliesFromApplicationBaseDirectory();
y.LookForRegistries();
});
});
return ObjectFactory.Container;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4292 次 |
最近记录: |