我在使用在 DefaultControllerFactory 中设置 DI 的 ASP.NET MVC 3 解决 Unity 2 中注册类型的命名注册时遇到问题。
在一个程序集中,我定义了具有注册类型和命名注册的 Unity 容器
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 );
它返回正确的类型。
有人知道出了什么问题吗?