3
everyone!使用MVC3解析來自Unity 2.0的命名註冊IDependencyResolver
我在使用MVC3 IDependencyResolver從Unity 2.0解析命名註冊時遇到問題。
我配置的類型登記爲
public class Implementations
{
private IUnityContainer unityContainer;
internal Implementations()
{
this.unityContainer = new UnityContainer();
}
public static IUnityContainer GetUnityContainer()
{
Implementations implementations = new Implementations();
implementations.RegisterImplementations();
return implementations.unityContainer;
}
private void RegisterImplementations()
{
this.unityContainer
.RegisterType<IService, TestService>()
.RegisterType<IService, TestService2>("ts2");
}
}
代碼的IDependencyResolver是
public class UnityDependencyResolver : IDependencyResolver
{
IUnityContainer container = null;
string namedRegistration = null;
public UnityDependencyResolver(IUnityContainer container, string name)
{
this.container = container;
this.namedRegistration = name;
}
public object GetService(Type serviceType)
{
try
{
return this.container.Resolve(serviceType, this.namedRegistration);
}
catch
{
return null;
}
}
public IEnumerable<object> GetServices(Type serviceType)
{
try
{
return this.container.ResolveAll(serviceType);
}
catch
{
return new List<object>();
}
}
}
和方法調用中的Application_Start是
protected void Application_Start()
{
var dependency =
new UnityDependencyResolver(Implementations.GetUnityContainer(), "ts2");
DependencyResolver.SetResolver(dependency);
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
我想這樣做,無論是在UnityDependencyResolver或任何其他方式,是解決我的命名實例或默認實例如果命名不存在。當前代碼總是解析爲默認實例(不命名)。
有沒有人有想法如何做到這一點?
謝謝。
您是否找到解決方案?我需要完全相同! –