Child container registration based on route parameters - c#

We have a multi-tennant ASP.NET MVC application that hosts a booking engine for multiple clients. Each of these clients has multiple packages that can influence Unity Container configuration. We are creating a child container per request and registering different interface implementations based on the client and package parameters passed through the route.
Currently we are accomplishing this by doing the following:
Controller has a property ServiceLocator that uses a unity container to resolve dependencies.
Controller gets IUnityContainer injected and assigned to a property.
Controller has a custom ActionFilterAttribute that accesses the controllers unity container, creates a child container, conditionally registers dependency implementations based on client and package route parameters, then assigns this child container to the controller's serviceLocator.
Controller uses serviceLocator on demand to resolve individual dependencies.
This works but is really clumsy and I feel eventually it will be unsustainable. I'm looking for a better solution.
We're stuck on .NET 4.0 at the moment until we wrap up some legacy stuff so I'm targeting Unity 2 specifically.
I've tried creating a custom IDependencyResolver to create the child container and register dependencies based on route parameters storing the container in either Session or in HttpContext items but ran into the null HttpContext problems. Is there any other way to base registrations on the route and have the dependencies injected to the controller constructor?
Eventually I will need a solution for Web API as well.
Edit: Example
public interface IRateService { ... }
public class RemoteRateService : IRateService { ... }
public class LocalRateService : IRateService { ... }
public class CustomDependencyResolver : IDependencyResolver
{
public object GetService(Type serviceType)
{
if(ChildContainer == null)
{
ChildContainer = _container.CreateChildContainer();
var routeData = HttpContext.Current.Request.RequestContext.RouteData.Values;
if(routeData["client"] == "ClientA")
ChildContainer.RegisterType<IRateService, RemoteRateService>();
else
ChildContainer.RegisterType<IRateService, LocalRateService>();
}
return ChildContainer.Resolve(serviceType);
}
}
public class RateController : Controller
{
private IRateService _rateService;
public RateController(IRateService rateService)
{
_rateService = rateService;
}
...
}
url: /ClientA/Package1/Rate - RateController gets RemoteRateService
url: /ClientB/Package2/Rate - RateController gets LocalRateService

Abatishchev answered my question in the comments by pointing me in the right direction with IControllerFactory. For the random google searches that end here, here is the basic setup I used by inheriting from DefaultControllerFactory:
public class UnitySessionControllerFactory : DefaultControllerFactory
{
private const string HttpContextKey = "Container";
private readonly IUnityContainer _container;
public UnitySessionControllerFactory (IUnityContainer container)
{
_container = container;
}
protected IUnityContainer GetChildContainer(RequestContext requestContext)
{
var routeData = requestContext.RouteData.Values
?? new RouteValueDictionary();
var clientName = routeData["clientName"] as string;
var packageId = routeData["packageID"] as int?;
if (clientName == null)
throw new ArgumentException("ClientName not included in route parameters");
var childContainer = requestContext.HttpContext.Session[clientName + HttpContextKey] as IUnityContainer;
if (childContainer != null)
return childContainer;
requestContext.HttpContext.Session[clientName + HttpContextKey] = childContainer = _container.CreateChildContainer();
var moduleLoader = childContainer.Resolve<ModuleLoader>();
moduleLoader.LoadModules(clientName, packageId);
return childContainer;
}
public override IController CreateController(RequestContext requestContext, string controllerName)
{
var controllerType = GetControllerType(requestContext, controllerName);
var container = GetChildContainer(requestContext);
return container.Resolve(controllerType) as IController;
}
public override void ReleaseController(IController controller)
{
_container.Teardown(controller);
}
}
Forgive the use of session here. In the future I will exchange it for HttpContext.Items once I am able to wrangle in our project's use of session.
To enable the custom controller factory I added this line to the Bootstrapper.Initialise() method
ControllerBuilder.Current
.SetControllerFactory(new UnitySessionControllerFactory(container));

Related

MVC with Castle Windsor RegisterForDispose

I have Castle Windsor Ioc in my MVC application. I have noticed that Objects tracked by release policy count is growing up all the time and as it seems this objects are never released(memory is growing up).
The code is:
public class ControllersInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(Classes.FromThisAssembly()
.BasedOn<IController>()
.LifestyleTransient());
}
}
In global.asax i have:
controllerFactory = new WindsorControllerFactory();
ControllerBuilder.Current.SetControllerFactory(controllerFactory);
controllerFactory.ValidateControllersResolution();
And class is:
public class WindsorControllerFactory: DefaultControllerFactory{
private readonly IWindsorContainer container;
public WindsorControllerFactory()
{
container = new WindsorContainer()
.Install(FromAssembly.This())
.AddFacility<WcfFacility>();
default policy is: LifecycledComponentsReleasePolicy
//container.Kernel.ReleasePolicy;
}
public override void ReleaseController(IController controller)
{
//this is called after each view return
container.Kernel.ReleaseComponent(controller);
}
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
if (controllerType == null)
{
throw new HttpException(404,
$"The controller for path '{requestContext.HttpContext.Request.Path}' could not be found.");
}
var controller= ((IController)container.Kernel.Resolve(controllerType)).AddControllerLoggingFunctionality();
return controller;
}
public void DisposeContainer()
{//this is never executed
container.Dispose();
}
In WEB API version: Web API with Castle Windsor
there is register for dispose before returning controller:
request.RegisterForDispose(
new Release(
() => this.container.Release(controller)));
But in my case there is RequestContext instead of HttpRequestMessage, which doesn't have RegisterForDispose method. Is there some other way to register for dispose or some other way to dispose controller after view is returned?
Or I'm not on the right track?
The RegisterForDispose() method only exists on HttpRequestMessage because it is capable of associating arbitrary objects with the request for the duration of the request through its Properties collection. Even the framework itself uses it (in GetOwinContext(), for example).
On the other hand, the traditional HttpRequest (that is available for MVC controllers) does not expose this capability* hence no RegisterForDispose() is provided.
* (Although you can associate arbitrary items to the HttpContext.Items, that is generally used to pass data between modules. If you were to use it to associate items to the current request, you'll have to dispose them manually as well

Dependency Injection in ASP.net Session_Start method

I am learning dependency injection and using autofac for the first time. I built the container as mentioned in several autofac examples (see below) and called from my application_start
public class ContainerConfig
{
public static void RegisterContainer()
{
//Create a new ContainerBuilder
var builder = new ContainerBuilder();
// Register all the controllers using the assembly object
builder.RegisterControllers(Assembly.GetExecutingAssembly());
//Registering default convention -- IExample and Example
builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
.Where(t => t.Name.Single(i => i.Name == "I" + t.Name))
.AsImplementedInterfaces();
//Build the container
var container = builder.Build();
//Set the default resolver to use Autofac
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
}
I created UserService in my Core project with IUserService. This has methods to make dbcall to get user information from tables. In my UI project, i have a class called UserProvider to which i am tying to inject UserService.
public class UserProvider
{
private readonly IUserService _userService;
public UserProvider(IUserService userService)
{
_userService = userService;
}
public void LoadCurrentUser()
{
Users FoundUser = _userService.ImportOrGetUser();
if (FoundUser != null)
{
//add it to session
CurrentUser = FoundUser;
}
}
}
This UserProvider, i am using in my session_start
void Session_OnStart()
{
UserProvider OUsrPrv = new UserProvider(new UserService());
OUsrPrv.LoadCurrentUser();
}
In the above code, if i am passing 'new UserService()', my understanding is i am injecting UserService manually. I dont see how autofac is helping here. All the examples in google are talking about Dependency injection in MVCController or WebApiController, not in a individual class (UserProvider) like i am doing.
Can somebody please throw some light? Am I doing it all wrong?
In order to properly use Dependency Injection, you should never create instance by yourself, the underlying framework should provide instances for you.
But ASP.net invokes the Session_OnStart without any Dependency Injection. In this case you can use the DependencyResolver.Current static property to resolve the requested service.
void Session_OnStart()
{
UserProvider userProvider = DependencyResolver.Current.GetService<UserProvider>();
userProvider.LoadCurrentUser();
}
The event model in the System.Web.HttpApplication is part of ASP.NET, not MVC. It was not designed for use with dependency injection.
The answer that Cyril suggested is using a service locator to get a reference to the service. This is far from ideal, since you are taking on a dependency to the service locator in your code.
The MVC-centric way of implementing cross cutting concerns (such as loading user data into session state) is to use globally registered filters. You can either implement IAuthorizationFilter or IActionFilter to get the desired effect. In this case it makes sense to use IActionFilter since you want to wait until you are sure there is an authorized user before it is called.
NOTE: While this answers your specific question, it is best not to use session state for this scenario in MVC. An alternative is to use ASP.NET Identity with Claims to store user profile data instead of using Session.
using System;
using System.Web.Mvc;
using System.Security.Principal;
public class GetUserActionFilter : IActionFilter
{
private readonly IUserRepository userRepository;
public GetUserActionFilter(IUserRepository userRepository)
{
if (userRepository == null)
throw new ArgumentNullException("userRepository");
this.userRepository = userRepository;
}
public void OnActionExecuted(ActionExecutedContext filterContext)
{
// Do nothing - this occurs after the action method has run
}
public void OnActionExecuting(ActionExecutingContext filterContext)
{
IPrincipal user = filterContext.HttpContext.User;
if (user == null)
{
return;
}
IIdentity identity = user.Identity;
if (identity == null)
{
return;
}
// Make sure we have a valid identity and it is logged in.
if (identity.IsAuthenticated)
{
string key = "__CurrentUserData";
var userData = filterContext.HttpContext.Session[key];
if (userData == null)
{
// User data doesn't exist in session, so load it
userData = userRepository.GetUserData(identity.Name);
// Add it to session state
filterContext.HttpContext.Session[key] = userData;
}
}
}
}
Now, to add your filter globally, you need to:
Register the filter and its dependencies with Autofac.
Pass the container to the static RegisterGlobalFilters method.
Register the Filter
Using a named instance to differentiate it from other potential IActionFilter instances.
builder.RegisterType<GetUserActionFilter>()
.Named<IActionFilter>("getUserActionFilter");
Pass the Container
FilterConfig.cs
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters, IContainer container)
{
filters.Add(container.ResolveNamed<IActionFilter>("getUserActionFilter"));
filters.Add(new HandleErrorAttribute());
}
}
Global.asax.cs
public class MvcApplication : System.Web.HttpApplication
{
// This method serves as the composition root
// for the project.
protected void Application_Start()
{
// Register Autofac DI
IContainer container = ContainerConfig.RegisterContainer();
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters, container);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
}
}
ContainerConfig.cs
public class ContainerConfig
{
public static IContainer RegisterContainer()
{
//Create a new ContainerBuilder
var builder = new ContainerBuilder();
// Register all the controllers using the assembly object
builder.RegisterControllers(Assembly.GetExecutingAssembly());
//Registering default convention -- IExample and Example
builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
.Where(t => t.Name.Single(i => i.Name == "I" + t.Name))
.AsImplementedInterfaces();
// Register our filter
builder.RegisterType<GetUserActionFilter>()
.Named<IActionFilter>("getUserActionFilter");
//Build the container
var container = builder.Build();
//Set the default resolver to use Autofac
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
// Return the container to our composition root.
return container;
}
}
Note that I just used a repository service here, since HttpContext is available already through the action filter directly and additional logic is needed here because we don't know for sure if it exists in session state or not or whether there is even a user to lookup, so our filter does those checks in addition to loading session state.

Autofac Registering Multiple Containers

I have a MVC application, and i am using Autofac to resolve dependencies.
I have a situation where i have to create 2 containers and runtime should decide which container to use based on a condition.
The condition is if the controller Home is called, i need to use container1, or else i have to use container2.
Application_Start is the place where I register the container.
I am not sure how to make this happen at runtime. Any help is highly appreciated.
Thanks
One reason for letting controllers resolve from different containers is if your application consists of multiple isolated modules. In that case you might not want the modules to influence each other and having a container per module makes sense. In almost all other situations however, it doesn't make sense to have multiple container instances.
So if you need this, you need to build your own custom IControllerFactory that can switch containers based on the controller type. For instance, something like this:
internal sealed class MultiplContainerControllerFactory : IControllerFactory
{
public IController CreateController(RequestContext requestContext, string controllerName)
{
var factory = this.GetFactory(requestContext);
var controller = factory.CreateController(requestContext, controllerName);
// By storing the factory in the request items for this controller,
// we allow it to be easily retrieved
// during ReleaseController and delegate releasing to the correct controller.
HttpContext.Current.Items["ContrFct_" + controller.GetType().FullName] = factory;
return controller;
}
public SessionStateBehavior GetControllerSessionBehavior(RequestContext requestContext,
string controllerName)
{
var factory = this.GetFactory(requestContext);
return factory.GetControllerSessionBehavior(requestContext, controllerName);
}
public void ReleaseController(IController controller)
{
var controllerFactory = (IControllerFactory)HttpContext.Current.Items["ContrFct_" +
controller.GetType().FullName];
controllerFactory.ReleaseController(controller);
}
private IControllerFactory GetFactory(RequestContext context)
{
// return the module specific factory based on the requestcontext
}
}
Besides this, you will need to have a special AutofacControllerFactory per container. That could look something like this:
public sealed class AutofacControllerFactory : DefaultControllerFactory
{
public readonly IContainer Container;
private readonly string moduleName;
public AutofacControllerFactory(IContainer container, string moduleName)
{
this.Container = container;
this.moduleName = moduleName;
}
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
if (controllerType == null)
{
// The base method throws an expressive 404 HTTP error.
base.GetControllerInstance(requestContext, controllerType);
}
// We need to start a new lifetime scope when resolving a controller.
// NOTE: We can apply MatchingScopeLifetimeTags.RequestLifetimeScopeTag to the BeginLifetimeScope
// method and in this case we can use .InstancePerRequest(), but in that case it becomes impossible to
// verify the DI configuration in an integration test.
ILifetimeScope lifetimeScope = this.Container.BeginLifetimeScope();
// We need to store this lifetime scope during the request to allow to retrieve it when the controller
// is released and to allow to dispose the scope. Memory leaks will be ensured if we don't do this.
HttpContext.Current.Items[controllerType.FullName + "_lifetimeScope"] = lifetimeScope;
// This call will throw an exception when we start making registrations with .InstancePerRequest,
// because the WebRequest functionality of Autofac is tied to the AutofacDependencyResolver, which we
// don't use here. We can't use the AutofacDependencyResolver here, since it stores the created lifetime
// scope in the HttpContext.Items, but it uses a fixed key, which means that if we resolve multiple
// controllers for different application modules, they will all reuse the same lifetime scope, while
// this scope originates from a single container.
try
{
return (IController)lifetimeScope.Resolve(controllerType);
}
catch (Exception ex)
{
lifetimeScope.Dispose();
throw new InvalidOperationException("The container of module '" + this.moduleName +
"' failed to resolve controller " + controllerType.FullName + ". " + ex.Message, ex);
}
}
[DebuggerStepThrough]
public override void ReleaseController(IController controller)
{
try
{
base.ReleaseController(controller);
}
finally
{
var scope = (ILifetimeScope)HttpContext.Current
.Items[controller.GetType().FullName + "_lifetimeScope"];
scope.Dispose();
}
}
}

Simple Injector: Different DbContext for selected controllers

I am trying to separate reads/writes in my MVC application. I am using Simple Injector as Ioc and I have following structure:
new Service(
new Repository(
new UnitOfWork(
new DbContext())))
So UnitOfWork registered per web request all the rest Transient.
So idea was to create separate read-only controllers and make a registration of DbContext to supply a different connection if controller is read-only. And that could be achievable with improved RegisterWithContext extension BUT it will not work in my case because not all graph nodes are Transient.
Is there any way (more elegant than register each Repository with improved RegisterWithContext extension where need to supply another read-only UnitOfWork and manually resolve all other arguments that passed into Repository) how the described scenario can be achieved?
Since the choice is based on the type of controller, you can make the descision in a custom IControllerFactory. For instance:
public class ConnectionSelector {
public bool AsReadOnly { get; set; }
}
private class ReadOnlySwitchControllerFactory : DefaultControllerFactory {
private readonly Container container;
public ReadOnlySwitchControllerFactory(Container container) {
this.container = container;
}
protected override IController GetControllerInstance(RequestContext requestContext,
Type controllerType) {
var selector = this.container.GetInstance<ConnectionSelector>();
selector.AsReadOnly =
typeof(IReadOnlyController).IsAssignableFrom(controllerType);
return base.GetControllerInstance(requestContext, controllerType);
}
}
You can register this as follows:
container.RegisterPerWebRequest<ConnectionSelector>();
container.RegisterPerWebRequest<DbContext>(() => new DbContext(
container.GetInstance<ConnectionSelector>().AsReadOnly
? "ReadOnlyConnection"
: "NormalConnection"));
container.RegisterSingle<IControllerFactory>(
new ReadOnlySwitchControllerFactory(container));

Exception is: InvalidOperationException - The current type, is an interface and cannot be constructed. Are you missing a type mapping?

In my bootstrapper:
namespace Conduit.Mam.ClientServices.Common.Initizliaer
{
public static class Initializer
{
private static bool isInitialize;
private static readonly object LockObj = new object();
private static IUnityContainer defaultContainer = new UnityContainer();
static Initializer()
{
Initialize();
}
public static void Initialize()
{
if (isInitialize)
return;
lock (LockObj)
{
IUnityContainer container = defaultContainer;
//registering Unity for MVC
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
//registering Unity for web API
// GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);
#region managers
container.RegisterType<ISettingsManager, SettingsManager>();
container.RegisterType<IMamDataManager, MamDataManager>();
container.RegisterType<IAppsDataManager, AppsDataManager>();
#endregion
if (!isInitialize)
{
isInitialize = true;
}
}
}
}
}
in my controller's code:
ISettingsManager sm = mUnityContainer.Resolve<ISettingsManager>();
hovering on mUnityContainer I see ISettingsManager is mapped to SettingsManager
but then I get the error:
Exception is: InvalidOperationException - The current type, is an
interface and cannot be constructed. Are you missing a type mapping?
I have also tried
ISettingsManager sm = (ISettingsManager)mUnityContainer.Resolve<>(typeof(ISettingsManager));
but no use
Just for others (like me) who might have faced the above error. The solution in simple terms.
You might have missed to register your Interface and class (which implements that inteface) registration in your code.
e.g if the error is
"The current type, xyznamespace. Imyinterfacename, is an interface and cannot be constructed. Are you missing a type mapping?"
Then you must register the class which implements the Imyinterfacename in the UnityConfig class in the Register method. using code like below
container.RegisterType<Imyinterfacename, myinterfaceimplclassname>();
You are incorrectly using Dependency Injection. The proper way is to have your controllers take the dependencies they need and leave to the dependency injection framework inject the concrete instances:
public class HomeController: Controller
{
private readonly ISettingsManager settingsManager;
public HomeController(ISettingsManager settingsManager)
{
this.settingsManager = settingsManager;
}
public ActionResult Index()
{
// you could use the this.settingsManager here
}
}
As you can see in this example the controller doesn't know anything about the container. And that's how it should be.
All the DI wiring should happen in your Bootstraper. You should never use container.Resolve<> calls in your code.
As far as your error is concerned, probably the mUnityContainer you are using inside your controller is not the same instance as the one constructed in your Bootstraper. But since you shouldn't be using any container code in your controllers, this shouldn't be a problem anymore.
In my case, I was getting this error despite registering an existing instance for the interface in question.
Turned out, it was because I was using Unity in WebForms by way of the Unity.WebForms Nuget package, and I had specified a Hierarchical Lifetime manager for the dependency I was providing an instance for, yet a Transient lifetime manager for a subsequent type that depended on the previous type - not usually an issue - but with Unity.WebForms, the lifetime managers work a little differently... your injected types seem to require a Hierarchical lifetime manager, but a new container is still created for every web request (because of the architecture of web forms I guess) as explained excellently in this post.
Anyway, I resolved it by simply not specifying a lifetime manager for the types/instances when registering them.
i.e.
container.RegisterInstance<IMapper>(MappingConfig.GetMapper(), new HierarchicalLifetimeManager());
container.RegisterType<IUserContext, UserContext>(new TransientLifetimeManager());
becomes
container.RegisterInstance<IMapper>(MappingConfig.GetMapper());
container.RegisterType<IUserContext, UserContext>();
So that IMapper can be resolved successfully here:
public class UserContext : BaseContext, IUserContext
{
public UserContext(IMapper _mapper) : base(_mapper)
{
}
...
}
In my case, I have used 2 different context with Unitofwork and Ioc container so i see this problem insistanting while service layer try to make inject second repository to DI. The reason is that exist module has containing other module instance and container supposed to gettng a call from not constractured new repository.. i write here for whome in my shooes
May be You are not registering the Controllers.
Try below code:
Step 1.
Write your own controller factory class
ControllerFactory :DefaultControllerFactory by implementing defaultcontrollerfactory
in models folder
public class ControllerFactory :DefaultControllerFactory
{
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
try
{
if (controllerType == null)
throw new ArgumentNullException("controllerType");
if (!typeof(IController).IsAssignableFrom(controllerType))
throw new ArgumentException(string.Format(
"Type requested is not a controller: {0}",
controllerType.Name),
"controllerType");
return MvcUnityContainer.Container.Resolve(controllerType) as IController;
}
catch
{
return null;
}
}
public static class MvcUnityContainer
{
public static UnityContainer Container { get; set; }
}
}
Step 2:Regigster it in BootStrap:
inBuildUnityContainer method
private static IUnityContainer BuildUnityContainer()
{
var container = new UnityContainer();
// register all your components with the container here
// it is NOT necessary to register your controllers
// e.g. container.RegisterType<ITestService, TestService>();
//RegisterTypes(container);
container = new UnityContainer();
container.RegisterType<IProductRepository, ProductRepository>();
MvcUnityContainer.Container = container;
return container;
}
Step 3:
In Global Asax.
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
Bootstrapper.Initialise();
ControllerBuilder.Current.SetControllerFactory(typeof(ControllerFactory));
}
And you are done
I had this problem, and the cause was that I had not added the Microsoft.Owin.Host.SystemWeb NuGet package to my project. Although the code in my startup class was correct, it was not being executed.
So if you're trying to solve this problem, put a breakpoint in the code where you do the Unity registrations. If you don't hit it, your dependency injection isn't going to work.
Below code will be helpful for you
public static IUnityContainer Initialise(IUnityContainer container = null)
{
if (container == null)
{
container = new UnityContainer();
}
container.RegisterType<ISettingsManager, SettingsManager>();
container.Resolve<SettingsManager>();
container.RegisterType<SettingsManagerController>(new InjectionProperty("_SettingManagerProvider", new ResolvedParameter<ISettingManager>()));
return container;
}

Categories