Why is autofac disposing an object before the HttpRequest ends? - asp.net-mvc

I'm writing an ASP.NET MVC website, using autofac for dependency injection, and Mindscape's Lightspeed as the ORM. There's a UserRepository class, which depends on a lightspeed UnitOfWork, and which services the Logon controller.
Problem: The UnitOfWork gets disposed before the UserRepository is finished using it.
public class UserRepository : IUserRepository
{
private readonly BluechipModelUnitOfWork _unitOfWork;
public UserRepository(BluechipModelUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
public Principal GetPrincipal(string name)
{
// This line throws an ObjectDisposedException - UnitOfWork is already disposed.
return _unitOfWork.Principals.FirstOrDefault(p => p.Name == name);
}
...
In Global.asax, the dependency wiring is done as follows:
public class MvcApplication : HttpApplication, IContainerProviderAccessor
{
private static void RegisterAutofac()
{
var builder = new ContainerBuilder();
// Register the lightspeed context as a singleton
builder.RegisterInstance(new LightSpeedContext<BluechipModelUnitOfWork>("LightSpeedBluechip"))
.As<LightSpeedContext<BluechipModelUnitOfWork>>()
.SingleInstance();
// Register the unit of work constructor so that a new instance is bound to each HttpRequest
builder.Register(c => c.Resolve<LightSpeedContext<BluechipModelUnitOfWork>>().CreateUnitOfWork())
.As<BluechipModelUnitOfWork>()
.InstancePerLifetimeScope();
// Register user repository to be one instance per HttpRequest lifetime
builder.Register(c => new UserRepository(c.Resolve<BluechipModelUnitOfWork>()))
.As<IUserRepository>()
.InstancePerLifetimeScope();
builder.Register(c => new CurrentUserService(
c.Resolve<HttpSessionState>(),
c.Resolve<IUserRepository>(),
c.Resolve<IMembershipService>())
).As<ICurrentUserService>()
.CacheInSession();
builder.RegisterType<ExtensibleActionInvoker>().As<IActionInvoker>();
builder.RegisterControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired().InjectActionInvoker();
builder.RegisterModelBinders(Assembly.GetExecutingAssembly());
// Set the container provider up with registrations.
_containerProvider = new ContainerProvider(builder.Build());
// Set the controller factory using the container provider.
ControllerBuilder.Current.SetControllerFactory(new AutofacControllerFactory(_containerProvider));
Given the above registrations, why would autofac be disposing the UnitOfWork (

I was able to track down the problem - it's a dumb but subtle gotcha...
I had a CurrentUserService class which I was registering as follows:
builder.Register(c => new CurrentUserService(
c.Resolve<HttpSessionState>(),
c.Resolve<IUserRepository>(),
c.Resolve<IMembershipService>())
).As<ICurrentUserService>()
.CacheInSession();
The problem is CacheInSession(), because the CurrentUserService depends on IUserRepository, which autofac was faithfully injecting, but then disposing of at the end of the first request.
This brings into light something obvious, yet subtle to be aware of when wiring up dependency injections:
Make sure that higher-order dependants always have the same or shorter lifetime as the services upon which they depend. In my case, the solution was to change the above code:
builder.Register(c => new CurrentUserService(
c.Resolve<HttpSessionState>(),
c.Resolve<IUserRepository>(),
c.Resolve<IMembershipService>())
).As<ICurrentUserService>()
.InstancePerLifetimeScope();
.... which prevents the CurrentUserService from out-living the instance upon which it depends.

Related

Register services with multiple lifetimes in unity

I use Unity in an MVC5 project (.net461) for DI and I want to register a service with multiple lifetimes.
With the classic core DI I would use RegisterScoped and that's it. Whenever the service is resolved within an Http Request I would reuse the same instance for the duration of the request. If I want to fire a background task, that background task should open a service scope, and I would resolve a new instance for the service for the duration of that scope. No need to have different registrations for the service. In the first case, the scope is created by the runtime, and in the second it is manually created by the developer. In both cases, the service provider only knows that the service is scoped, it doesn't care about where and how the scope has opened.
With Unity the first case is solved with PerRequestLifetimeManager. The second case is solved with a HierarchicalLifetimeManager.
But how should I have a combination of the two?
Whenever a service is resolved within an HttpRequest (in a controller constructor for instace) it should use the PerRequestLifetimeManager and wherever it is resolved in a child container (within the constructor of another service that is instantiated in the child container) it should use HierarchicalLifetimeManager.
How can I register the service with both managers?
At the end of the day, I had to implement my own solution which is based on (but not using) Unity.Mvc, Unity.WebApi packages, and the HierarchicalLifetimeManager.
None of the solutions I found online worked for my case. Most of them covered only the per request part, but not the per custom user scope part.
The key of the solution is not the lifetime manager but the dependency resolver. The lifetime manager for my requirements should always be HierarchicalLifetimeManager because that is what I truly need. A new container for each scope, which is covered by child containers and HierarchicalLifetimeManager.
Using Integrating ASP.NET Core Dependency Injection in MVC 4 as an example on how to implement your own dependency resolver, I came up with the solution below.
What I had to do, is to make sure a new scope is created on the beginning of the Http Request, and Disposed at the end of the Http Request. This part is covered by implementing a simple HttpModule. This part is similar to the HttpModule used by the official Unity Per Request Lifetime implementation.
Per Http Request Module
This is the module implementation
internal class UnityPerHttpRequestModule : IHttpModule
{
private static IUnityContainer _rootContainer;
public void Init(HttpApplication context)
{
context.BeginRequest += (s, e) =>
((HttpApplication)s).Context.Items[typeof(UnityPerHttpRequestModule)]
= _rootContainer.CreateChildContainer();
context.EndRequest += (s, e) =>
(((HttpApplication)s).Context.Items[typeof(UnityPerHttpRequestModule)]
as IUnityContainer)?.Dispose();
}
public static void SetRootContainer(IUnityContainer rootContainer)
{
_rootContainer = rootContainer ?? throw new ArgumentNullException(nameof(rootContainer));
}
public void Dispose() { }
}
On Beginning the request we create a new child container and place it in the HttpRequest Items dictionary.
On Ending the request we retrieve the child container from the Items dictionary and dispose it.
The static method SetRootContainer should be called once at the startup of the application to pass in the initial root Unity container, the one that services are registered on.
public class Global : HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
UnityPerHttpRequestModule.SetRootContainer(UnityConfig.Container); // pass here the root container instance
...
}
}
We also need to register the module with owin.
using Microsoft.Owin;
using Microsoft.Web.Infrastructure.DynamicModuleHelper;
using Owin;
[assembly: OwinStartup(typeof(MyApp.Startup))]
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(MyApp.Startup), nameof(MyApp.Startup.InitScopedServicesModule))]
namespace MyApp
{
public partial class Startup
{
public static void InitScopedServicesModule()
{
DynamicModuleUtility.RegisterModule(typeof(UnityPerHttpRequestModule));
}
public void Configuration(IAppBuilder app)
{
}
}
}
MVC Dependency Resolver
Now the http module is registered and we have a new scope created on each request. Now we need to instruct MVC and WebApi to use that scope. For this, we need to create the appropriate dependency resolvers. I created one dependency resolver for MVC and one for WebApi since they need to implement different interfaces (I could have implemented both in the same class though).
The dependency resolver for MVC is this:
internal class UnityMvcPerHttpRequestDependencyResolver : IDependencyResolver
{
private readonly IUnityContainer rootContainer;
internal UnityMvcPerHttpRequestDependencyResolver(IUnityContainer rootContainer)
{
this.rootContainer = rootContainer;
}
internal IUnityContainer Current => (HttpContext.Current?.Items[typeof(UnityPerHttpRequestModule)] as IUnityContainer) ?? this.rootContainer;
public void Dispose() { }
public object GetService(Type serviceType)
{
try
{
return Current.Resolve(serviceType);
}
catch (ResolutionFailedException)
{
return null;
}
}
public IEnumerable<object> GetServices(Type serviceType)
{
try
{
return Current.ResolveAll(serviceType);
}
catch (ResolutionFailedException)
{
return null;
}
}
}
What the resolver does is that it checks for an HTTP Context and gets the unity container in the Context's item dictionary and uses this container to resolve the services. So effectively, if the service requested is registered with a Hierarchical Lifetime, a new instance of that service will be created within the child container (aka within the context of the request). Since the child container is disposed at the end of the request by the http module, any services instantiated in the child container are also disposed.
Things to notice here:
The IDependencyResolver interface here is the System.Web.Mvc.IDependencyResolver. This is the interface expected by the MVC. The WebApi expects a difference IDependencyResolver (same name, different namespaces)
Catching ResolutionFailedException. If you don't catch those exceptions, the application will crash.
Now that we have the MVC dependecy resolver, we need to instruct MVC to use this resolver.
public static class UnityMvcActivator
{
public static void Start()
{
FilterProviders.Providers.Remove(FilterProviders.Providers.OfType<FilterAttributeFilterProvider>().First());
FilterProviders.Providers.Add(new UnityFilterAttributeFilterProvider(UnityConfig.Container));
//DependencyResolver.SetResolver(new UnityDependencyResolver(UnityConfig.Container));
DependencyResolver.SetResolver(new UnityMvcPerHttpRequestDependencyResolver(UnityConfig.Container));
// TODO: Uncomment if you want to use PerRequestLifetimeManager
//Microsoft.Web.Infrastructure.DynamicModuleHelper.DynamicModuleUtility.RegisterModule(typeof(UnityPerRequestHttpModule));
}
}
Things to notice here:
Do not register the official UnityPerRequestHttpModule since we implement our own. ( I could probably use that module but my implementation would depend on the inner implementation of the official module and I don't want that, since it may change later)
Web Api Dependency Resolver
Simlilar to MVC dependency resolver, we need to implement one for the Web Api
internal class UnityWebApiPerHttpRequestDependencyResolver : IDependencyResolver
{
private readonly IUnityContainer rootContainer;
internal UnityWebApiPerHttpRequestDependencyResolver(IUnityContainer rootContainer)
{
this.rootContainer = rootContainer;
}
internal IUnityContainer Current => (HttpContext.Current?.Items[typeof(UnityPerHttpRequestModule)] as IUnityContainer) ?? this.rootContainer;
public IDependencyScope BeginScope() => this;
// Dispose, GetService and GetServices are the same as MVC dependency resolver
}
Things to notice here:
IDependencyResolver here is of type System.Web.Http.Dependencies.IDependencyResolver. It is not the same as MVC's IDependencyResolver.
This Dependency resolver interface implements one more method: BeginScope. This is important here. WebApi pipeline is different that MVC pipeline. WebApi engine, by default, calls BeginScope to open a new scope for each web api request, and uses that scope to resolve controllers and services. So, Web api has already a scoped mechanism. BUT we have already created a scope ourselves with our per request module and we want to use that scope. So what we have to do here is to not create a new scope again. It already exists. So calling BeginScope on our resolver should return the same resolver scope, thus we return this.
Now that we have created the WebApi resolver, we have to also register it to web api.
using System.Web.Http;
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(MyApp.UnityWebApiActivator), nameof(MyApp.UnityWebApiActivator.Start))]
namespace MyApp
{
/// <summary>
/// Provides the bootstrapping for integrating Unity with WebApi when it is hosted in ASP.NET.
/// </summary>
public static class UnityWebApiActivator
{
/// <summary>
/// Integrates Unity when the application starts.
/// </summary>
public static void Start()
{
// Use UnityHierarchicalDependencyResolver if you want to use
// a new child container for each IHttpController resolution.
// var resolver = new UnityHierarchicalDependencyResolver(UnityConfig.Container);
var resolver = new UnityWebApiPerHttpRequestDependencyResolver(UnityConfig.Container);
GlobalConfiguration.Configuration.DependencyResolver = resolver;
}
}
}
Registering services
Now that we have set up and registered all our Resolvers and modules, the last thing to do is to remember to register each scoped service with HierarchicalLifetimeManager. Since our scoped solution depends on child containers, registering our scoped services that way will suffice.
Conclusion
And with that, I managed to implement a working scoped DI solution with Unity. The example below did not work with the official Per Request Lifetime solution, but worked with my custom implementation.
class TestController{
private readonly IMyScopedService service;
private readonly IUnityContainer container;
public TestController(IUnityContainer container, IMyScopedService service){
this.service = service;
this.container = container;
}
public ActionResult Post( ... ){
var childContainer = this.container.CreateChildContainer();
var scopedService = childContainer.GetService<IMyScopedService>()
HostingEnviroment.QueueBackgroundWorkItem(() => {
using(childContainer){
scopedService.DoWork();
}
});
}
}
With the official PerRequestLifetimeManager solution, this.service and scopedService were the same instance. The scoped service was instantiated in the http context, then the same instance was fetched again from the child container (since it was registerd with PerRequestLifetimeManager and not HierarchicalLifetimeManager) and passed to the background Job. The background job outlives the http request. The instance is disposed when the Http requests ends, but it is still being used in the background job which probably runs in another thread. Concurrency issues (and more) arise. For instance you can't use the same instance of an EF DbContext in multiple threads.
With the custom implementation above, the example works. scopedService is a different instance since it is registered with a HierarchicalLifetimeManager. this.services is disposed when the http request ends but scopedService lives during the whole execution of the background Job.
What we effectively do is control the lifetime of the services by controlling the lifetime of child containers. And I have the impression that this is the solution for every scoped service scenario.
Register all scoped services with HierarchicalLifetimeManager
Control the lifetime of services by controlling the lifetime of the child containers.

Autowiring properties in base classes not working in ASP.NET Core 2

I have a .Net Core 2 app and an API controller class which inherits from an abstract base class:
[Route("api/[controller]")]
public class MyController : BaseController
On the base controller I have:
public ICommandProcessor CommandProcessor { get; set; }
In my StartUp.cs I have:
builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
.Where(t => t.IsSubclassOf(typeof(BaseController)))
.PropertiesAutowired();
However, the CommandProcessor property is always null. I have tried moving it to the derived class and tried registering the type directly as follows:
builder.RegisterType<MyController>().PropertiesAutowired();
and the also the base class:
builder.RegisterType<BaseController>().PropertiesAutowired();
I have tried what is suggested here and here amongst other posts but nothing seems to work, which makes me think that it is an issue in .Net Core 2.
When I inject the ICommandProcessor into the controller constructer it is wired up fine.
It is worth mentioning that I have tried this on other class that is not a controller, registered in the following way in the startup:
builder.RegisterType<DomainEvents>().PropertiesAutowired();
and the property on that is still null also.
EDIT:
I have raised this on the autofac project page on github, and they have advised me to show the full ConfigureServices class, which is below:
public IServiceProvider ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc().AddControllersAsServices();
// Identity server
var builder = new ContainerBuilder();
builder.RegisterModule(new CoreImplementationModule());
builder.RegisterModule(new PortalCoreImplementationModule());
builder.Register((context, _) => new DocumentClient(
new Uri(Configuration["DocumentDb:Uri"]),
Configuration["DocumentDb:Key"],
null,
new ConsistencyLevel?()))
.As<IDocumentClient>();
builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
.Where(t => t.IsSubclassOf(typeof(BaseController)))
.PropertiesAutowired();
builder.Populate(services);
builder.RegisterType<DomainEvents>().PropertiesAutowired();
var container = builder.Build();
return new AutofacServiceProvider(container);
}

MVC SimpleInjector tries to inject in every constructor

I have a MVC project, where i want to register a singleton of a specific service.
When i use simpleinjector, i get an error in all of my other classes with multiple constructors and so on. How do i configure it so ONLY my wanted service is dependency injection and DI is disabled for everything else (like before i used the DI container)?
Example of an exception i get:
No registration for type AccountController could be found and an
implicit registration could not be made. For the container to be able
to create AccountController it should have only one public
constructor: it has 2.
But i don't want AccountController to use dependency injection?!
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
// Create IOC Container
var container = new Container();
// Register services
container.RegisterSingleton<IWebSocketHandler, WebSocketHandler>();
// Verify services
container.Verify();
// Store the container for use by the application
DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
}
}

SignalR 2 Dependency Injection with Ninject

I have an existing MVC application that is using Dependency Injection with Ninject. I installed the Ninject.MVC3 nuget package and it creates a class called NinjectWebCommon in my App_Start, which completely isolates the kernel and registers all of my bindings:
public static void Start()
{
DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
bootstrapper.Initialize(CreateKernel);
}
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
RegisterServices(kernel);
return kernel;
}
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IFoo>().To<Foo>();
}
We have a new requirement that we thought SignalR would be able to satisfy, so we installed SignalR 2 nuget package into the project. I created a Hub and did some searching on how to implement Dependency Injection into the project and found an article that suggests creating a SignalRDependencyResolver. http://www.asp.net/signalr/overview/signalr-20/extensibility/dependency-injection
The article has you creating a kernel in the Startup.cs file that is used for registering SignalR in OWIN:
public class Startup
{
public void Configuration(IAppBuilder app)
{
var kernel = new StandardKernel();
var resolver = new NinjectSignalRDependencyResolver(kernel);
kernel.Bind<IStockTicker>()
.To<Microsoft.AspNet.SignalR.StockTicker.StockTicker>() // Bind to StockTicker.
.InSingletonScope(); // Make it a singleton object.
kernel.Bind<IHubConnectionContext>().ToMethod(context =>
resolver.Resolve<IConnectionManager>().GetHubContext<StockTickerHub>().Clients
).WhenInjectedInto<IStockTicker>();
var config = new HubConfiguration()
{
Resolver = resolver
};
app.MapSignalR(config);
}
}
The problem is that this approach has me creating two different kernels and they seem to have their own set of dependencies that they know how to resolve. If I have a dependency defined in NinjectWebCommon, the Hub doesn't know how to resolve that dependency. Without exposing my kernel in NinjectWebCommon, what is the proper way to add DI into SignalR using the Ninject.MVC3 package?
None of the current answers directly answer your question. Also achieving the result you are after is very straightforward once you know exactly what to do. The "proper" way to do this is to set SignalR's dependency resolver in the CreateKernel method of the NinjectWebCommon class.
Assuming you have created a NinjectSignalRDependencyResolver class as you mention, no other code needs to be added anywhere except for the line highlighted in the code snippet below:
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
// THIS LINE DOES IT!!! Set our Ninject-based SignalRDependencyResolver as the SignalR resolver
GlobalHost.DependencyResolver = new NinjectSignalRDependencyResolver(kernel);
RegisterServices(kernel);
return kernel;
}
Apart from the above, nothing more needs to be done except declaring your bindings in the RegisterServices method of NinjectWebCommon. In your example this would look like:
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IStockTicker>()
.To<Microsoft.AspNet.SignalR.StockTicker.StockTicker>() // Bind to StockTicker.
.InSingletonScope(); // Make it a singleton object.
kernel.Bind<IHubConnectionContext>().ToMethod(context =>
resolver.Resolve<IConnectionManager>().GetHubContext<StockTickerHub>().Clients
).WhenInjectedInto<IStockTicker>();
}
Except for the NinjectSignalRDependencyResolver class you created, no other code needs to be added. Importanly, the OwinStartup class remains unmodified, as follows:
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
The above example achieves the following important outcomes which were what you asked in your question:
You only have a single Ninject Kernel created
The kernel and all binding configurations remain confined to NinjectWebCommon
The default SignalR resolver is your NinjectSignalRDependencyResolver
Dependency Injection into all SignalR hubs is achieved
Hopefully this helps people out.
Have you tried adding the StockTickerHub itself to your kernel?
By default, SignalR uses Activator.CreateInstance to construct Hubs without any constructor arguments. If you want to inject your own dependencies into a Hub, you can do so by registering the Hub with SignalR's dependency resolver.
https://github.com/SignalR/SignalR/blob/2.0.1/src/Microsoft.AspNet.SignalR.Core/Hubs/DefaultHubActivator.cs#L28
If you want to get really creative, you can register your own IHubActivator instead of registering all of Hubs individually.
I go into more detail in how Hubs are created by default in this answer: SignalR with IoC (Castle Windsor) - which lifetime for hubs?
There is a problem with the singleton scope. I donĀ“t know who should get the blame here (Ninject, SignalR, MVC, etc...), but it works if you use ToConstant:
var binding = Bind<IMustBeSingleton>().ToConstant(new MustBeSingleton());
I had the same problem, and I found the solution: SignalR, WebAPI and MVC sharing the same dependency resolver kernel
I shared a complete solution with MVC, WebAPI and SignalR using the same Ninject kernel: https://drive.google.com/file/d/0B52OsuSSsroNX0I5aWFFb1VrRm8/edit?usp=sharing
That example web app, contains a single page that shows the AppDomain and GetHashCode of an object that is supposed to be unique across the three frameworks, giving a result similar to:
Dependency Test
Framework IMySingletonService instance
MVC AppDomainId:2 / HashCode:5109846
WebAPI AppDomainId:2 / HashCode:5109846
SignalR AppDomainId:2 / HashCode:5109846
I hope this helps.

mvc injecting httpcontext into service layer

I have having a big issue while injecting httpContextBase into my a service level object injected into controller using unity.
sample controller
public HomeController : Controller{
private IWorkContext _context;
public HomeController(IWorkContext context){
_context = context;
}
}
public WorkContext : IWorkContext{
private HttpContextBase _httpContext;
public (HttpContextBase httpContext){
_httpContext = httpContext;
}
public void DealWithCookies(){
//do some thing with http context and deal with cookies
}
}
Inside unity bootstrapper
container.RegisterType<HttpContextBase>().RegisterInstance(new HttpContextWrapper(HttpContext.Current) as HttpContextBase, new ContainerControlledLifetimeManager());
//With this line httpcontextbase is returned but as a singleton instead of new for each request.
container.RegisterType<HttpContextBase>().RegisterInstance(new HttpContextWrapper(HttpContext.Current) as HttpContextBase, new PerRequestLifetimeManager());
//This line returns an exception
The type HttpContextBase does not have an accessible constructor.
I wouldn't inject the HttpContext at all - I would pass it into each method call:
public WorkContext : IWorkContext{
private HttpContextBase _httpContext;
public WorkContext(){
...
}
public void DealWithCookies(HttpContext ctx){
//do some thing with http context and deal with cookies
}
}
Trying to use dependency injection here seems to be a misappropriation of the principle to me. Dependency injection allows you to loosely-couple your components but there's no need for this here since you can pass the context into methods and manipulate it directly. There's no interface to provide a concrete implementation of so there's no benefit to DI - it's just unnecessary bootstrapping and an "anti-pattern" lack of structure.
Not to mention that you're not going to be able to do this anyway given that when you register your types on application launch, there's no instance to register (and the instance needs to change on each request).
On a side note - I hope that IWorkContext is solely for abstracting cookie logic and isn't a layer between your application and your data layer. If not, it shouldn't have a dependency on an HTTP context at all.
FYI
You can mock the http context into controller as per this article on TDD and MVC:
http://msdn.microsoft.com/en-us/library/ff847525(v=vs.100).aspx
Failing that to inject an instance of an HttpContextBase implementation do the following (works in my projects!!):
container.RegisterType(new InjectionFactory(c => new HttpContextWrapper(HttpContext.Current)));

Resources