我有一个使用ASP.NET MVC 3与DI在DefaultControllerFactory设置解决注册的类型在Unity 2的命名注册的问题。
在一个组件我已经定义统一容器登记类型和命名注册
public class VisUnityContainer : UnityContainer
{
public IUnityContainer RegisterVisComponents()
{
// register types
this
.RegisterType<ICompanyService, CompanyService>()
.RegisterType<ICompanyService, TestCompanyService>( "2" );
}
}
在我的MVC项目我继承DefaultControllerFactory我正在解决的类型和传递VisUnityContainer
public class UnityControllerFactory : DefaultControllerFactory
{
private readonly IUnityContainer unityContainer;
public UnityControllerFactory( IUnityContainer unityContainer )
{
// set contracts
if( unityContainer == null )
throw new ArgumentNullException( null, "Unity container is not initialized." );
// set associations
this.unityContainer = unityContainer;
}
protected override IController GetControllerInstance( RequestContext requestContext, Type controllerType )
{
// set contracts
if( controllerType == null )
throw new HttpException( 404, String.Format( "The controller for path '{0}' could not be found or it does not implement IController.",
requestContext.HttpContext.Request.Path ) );
if( !typeof( IController ).IsAssignableFrom( controllerType ) )
throw new ArgumentException( String.Format( "Type requested is not a controller: {0}", controllerType.Name ) );
// action result
IController controller;
// company law
string companyLaw = String.Empty;
// set user properties
if( Thread.CurrentPrincipal != null &&
Thread.CurrentPrincipal.Identity.Name != null &&
!String.IsNullOrWhiteSpace( Thread.CurrentPrincipal.Identity.Name ) )
{
// set culture for law of companies region
CultureInfo cultureInfo = new CultureInfo( Profile.GetCurrent().CompanyState );
// set language
CultureInfo uiCultureInfo = new CultureInfo( Profile.GetCurrent().UserLanguage );
// set dates etc.
Thread.CurrentThread.CurrentCulture = cultureInfo;
// get proper resource file
Thread.CurrentThread.CurrentUICulture = uiCultureInfo;
// set company law
companyLaw = Profile.GetCurrent().CompanyLaw;
}
try
{
// resolve container
controller = this.unityContainer.Resolve( controllerType, companyLaw ) as IController;
}
catch( Exception )
{
// throw exception
throw new InvalidOperationException( String.Format( "Error resolving controller {0}", controllerType.Name ) );
}
// action end
return controller;
}
}
问题是与线
controller = this.unityContainer.Resolve( controllerType, companyLaw ) as IController;
虽然companyLaw等于2它不能解决命名注册TestCompanyService,但总是CompanyService。 如果我还设置CompanyService一些命名注册,它抛出一个错误说,它不能解析的类型。
另外,如果我尝试手动解决型状
var test = this.unityContainer.Resolve<ICompanyService>( companyLaw );
它返回正确的类型。
没有任何人有一个想法有什么不对?