I have a problem with resolving registered registrations of registered types in Unity 2 using ASP.NET MVC 3 with the DI set to DefaultControllerFactory.
In one build, I defined a Unity container with registration types and named registrations
public class VisUnityContainer : UnityContainer
{
public IUnityContainer RegisterVisComponents()
{
this
.RegisterType<ICompanyService, CompanyService>()
.RegisterType<ICompanyService, TestCompanyService>( "2" );
}
}
and in my MVC project, I inherited DefaultControllerFactory. I resolve types and pass VisUnityContainer
public class UnityControllerFactory : DefaultControllerFactory
{
private readonly IUnityContainer unityContainer;
public UnityControllerFactory( IUnityContainer unityContainer )
{
if( unityContainer == null )
throw new ArgumentNullException( null, "Unity container is not initialized." );
this.unityContainer = unityContainer;
}
protected override IController GetControllerInstance( RequestContext requestContext, Type controllerType )
{
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 ) );
IController controller;
string companyLaw = String.Empty;
if( Thread.CurrentPrincipal != null &&
Thread.CurrentPrincipal.Identity.Name != null &&
!String.IsNullOrWhiteSpace( Thread.CurrentPrincipal.Identity.Name ) )
{
CultureInfo cultureInfo = new CultureInfo( Profile.GetCurrent().CompanyState );
CultureInfo uiCultureInfo = new CultureInfo( Profile.GetCurrent().UserLanguage );
Thread.CurrentThread.CurrentCulture = cultureInfo;
Thread.CurrentThread.CurrentUICulture = uiCultureInfo;
companyLaw = Profile.GetCurrent().CompanyLaw;
}
try
{
controller = this.unityContainer.Resolve( controllerType, companyLaw ) as IController;
}
catch( Exception )
{
throw new InvalidOperationException( String.Format( "Error resolving controller {0}", controllerType.Name ) );
}
return controller;
}
}
The problem is the line
controller = this.unityContainer.Resolve( controllerType, companyLaw ) as IController;
As long as companyLaw is 2, it does not allow the named registration of TestCompanyService, but always CompanyService. If I also installed CompanyService with some named registration, it throws an error stating that it cannot resolve the type.
Also, if I try to manually decide the type of type
var test = this.unityContainer.Resolve<ICompanyService>( companyLaw );
It returns the correct type.
- , ?