Unity to dispose of object - unity-container

Is there a way to make Unity dispose property-injected objects as part of the Teardown?
The background is that I am working on an application that uses ASP.NET MVC 2, Unity and WCF. We have written our own MVC controller factory that uses unity to instantiate the controller and WCF proxies are injected using the [Dependency] attribute on public properties of the controller. At the end of the page life cycle the ReleaseController method of the controller factory is called and we call IUnityContainer.Teardown(theMvcController). At that point the controller is disposed as expected but I also need to dispose the injected wcf-proxies. (Actually I need to call Close and/or Abort on them and not Dispose but that is a later problem.)
I could of course override the controllers' Dispose methods and clean up the proxies there, but I don't want the controllers to have to know about the lifecycles of the injected interfaces or even that they refer to WCF proxies.
If I need to write code myself for this - what would be the best extension point? I'd appreciate any pointer.

I've created a unity extension that will take care of disposing instances created by the container on TearDown.
See http://www.neovolve.com/2010/06/18/unity-extension-for-disposing-build-trees-on-teardown/

A possible workaround is that you could also write a wrapper around your proxies that will on dispose (called by Unity when disposing instances) call a Close method of the proxy. Is that a viable scenarion for you ?

Once you've got your UnityDependencyResolver
GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
You can then call Dispose on the resolver. In ASP.NET you might choose to call this from your Global.asax.cs Application_End method like this:
GlobalConfiguration.Configuration.DependencyResolver.Dispose();
This will then call dispose on all the stuff that have container lifetime, such as instances added to the container with:
var myFooInstance = new Foo();
container.RegisterInstance<IFoo>(myFooInstance);

Related

Get same instance of a component registered with Autofac as InstancePerLifetimeScope in Global.asax methods as is injected into a controllers?

I have a situation where I need to manually instantiate some objects in Application_BeginRequest that are dependent on some of the same components that I've registered with Autofac. I'd like to use the same instances of components that I've registered with Autofac with InstancePerLifetimeScope for injection into my MVC and WebAPI controllers. My config for both MVC and Web API works as expected, and an example of a component registration looks like so:
builder.Register(c => new MyDbContext()).AsSelf().InstancePerLifetimeScope();
Now I want to use that same instance in the class I'm instantiating in Application_BeginRequest. I've tried the following methods:
//Tried with MVC controllers
DependencyResolver.Current.GetService<MyDbContext>()));
AutofacDependencyResolver.Current.ApplicationContainer.Resolve<MyDbContext>()));
AutofacDependencyResolver.Current.RequestLifetimeScope.Resolve<MyDbContext>()));
//Tried with Web API controllers
GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(MyDbContext))
But none give me what I'm looking for, even at later points in the request lifecylce (ie, beyond BeginRequest). As an aside, I need this to work with the Web API configuration, but I tried the first 3 methods just to see if I could get any of the resolved instances to match up with what Autofac is injecting.
I have what I believe is a decent understanding of lifetime scopes in Autofac and my assumption is that the instances that are being resolved for my application's controllers are in a child scope that the none of the above 4 methods are pointed towards, but it's fuzzy to me what each of the above methods is trying to do in regard to which scope they are looking at and how they decide. What's even fuzzier is what lifetime scopes Autofac is automatically creating for the components that are ultimately injected into my controllers and when they're created.
Clarification on the points above would be a big bonus, but my primary question here is how do I get Autofac to hand me the same instances of registered components in Global.asax that it resolves for Web API and MVC controllers?
If you read up on this subject, you'll notice that folks mention that in most circumstances for a web application, InstancePerLifetimeScope and InstancePerRequest can be used interchangeably. What they don't mention are the exceptions where these two registrations behave differently. Gerrod has an excellent article on lifetime scopes inside of ASP.NET MVC/Web API applications and how they work in which he elaborates on this piece of info that most omit. Understanding this difference is crucial to this scenario, and his article cleared up any misunderstandings I had in regards to InstancePerLifetimeScope registration in relation to ASP.NET applications. It also made me realize that, because I need to share instances of resolved components across my MVC/Web API controllers and within the global.asax, InstancePerLifetimeScope is no longer a suitable means of registration for this application- I now need to use InstancePerRequest.
As per the docs, InstancePerRequest actually uses InstancePerMatchingLifetimeScope under the hood. What I need is a reference to the child scope that is tagged with "AutofacWebRequest" that lives under the root scope. This is the scope that both my MVC and Web API controllers resolve their dependencies from, since they both use the same tag. So how do I get a reference to that particular scope? This was my solution, and I'd love to know if there's a better way to do it.
First off, I need to change my registration from
builder.Register(c => new MyDbContext()).AsSelf().InstancePerLifetimeScope();
to
builder.Register(c => new MyDbContext()).AsSelf().InstancePerRequest();
Now, after I've built my container I have the following method:
private void SetDependencyResolversForMvcAndWebApi(ILifetimeScope container)
{
container.ChildLifetimeScopeBeginning += CaptureRequestLifetimeScope;
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);
}
The only part that wasn't there before is the event subscription. Everytime my container creates a child scope, my event handler gets called. The event handler looks like this:
private void CaptureRequestLifetimeScope(object sender, LifetimeScopeBeginningEventArgs args)
{
if (args.LifetimeScope.Tag == MatchingScopeLifetimeTags.RequestLifetimeScopeTag)
{
//Get the ILifetimeScope created for components registered with InstancePerRequest
var requestScope = args.LifetimeScope;
//This is the same DbContext instance that will be injected into
//my WebAPI and MVC controllers
var context = requestScope.Resolve<MyDbContext>();
//do the rest of my stuff
}
}
I've tested this by holding onto a reference of the resolved DbContext that's resolved within the CaptureRequestLifetimeScope event handler and comparing it to the DbContext instances that are injected into my Web API and MVC controllers, and they are indeed pointing to the same object.
Well, I think you should try changing .InstancePerLifetimeScope() into .InstancePerRequest();
As Autofac says about InstancePerLifetimeScope:
When you resolve the instance per lifetime scope component, you get a single instance per nested scope (e.g., per unit of work).
So when you do Resolve<MyDbContext>() you are probably doing it in a different Lifetime scope than you controller (I guess it's because you're doing an explicit resolution); that's why you're getting a diffent instance.
InstancePerRequest instead:
Some application types naturally lend themselves to “request” type semantics, for example ASP.NET web forms and MVC applications. In these application types, it’s helpful to have the ability to have a sort of “singleton per request.”
The begin phase of your request is already in the request phase, so you shoud get the same instance there and inside your controllers.
Instance per request builds on top of instance per matching lifetime scope by providing a well-known lifetime scope tag, a registration convenience method, and integration for common application types.
Based on this, probably, you can also go for the .InstancePerMatchingLifetimeScope("myrequest"), but you will have to manually instanciate a Lifetime scope everywhere like this using(var scope1 = container.BeginLifetimeScope("myrequest")); I think is not so practical.
Obviously I suppose you will not use those elements outside of the request scope, or you will get an exception. In that case, you are forced to the MatchingLifetimeScope.
If you need more details, the Autofac guide is extremely clear.
DependencyResolver.Current.GetService<MyDbContext>()));
AutofacDependencyResolver.Current.RequestLifetimeScope.Resolve<MyDbContext>()));
are same. They get current request lifetime scope. If you resolve some instance here, it shares it with cotrollers. (In this stiuation, instance per request and instance per lifetime will be same. Because their lifetime is same).
AutofacDependencyResolver.Current.ApplicationContainer.Resolve<MyDbContext>()));
This wil be resolved from root container. That's why it will create another instance for request lifetime scope. This will not be shared. And this will live in root container. (If you have per request instance, this will give error).
I have tested first one. It shares instance resolved in Application_BeginRequest with mvc controllers but not with Api controllers.
Then I tried to get GlobalConfiguration.Configuration.DependencyResolver.GetRequestLifetimeScope() in Application_BeginRequest it returns null.
I think, if it's api request, Autofac doesn't start request lifetime yet in Application_BeginRequest (May be it's related .net).
So if it's api request and if we can't reach autofac request life time. I don't know how to share this instance with mvc and api controllers which is resolved in Application_BeginRequest.
May be Travis can make it clear.

Using InjectionFactory to inject DbContext, lifetime of created instance

I have an ASP.NET MVC5 project with Unity as DI framework.
Consider the following code:
container.RegisterType<ApplicationDbContext>(
new InjectionFactory(c => new ApplicationDbContext()));
As my repositories are using the same DbContext, it would be practical to pass the same instance to all of them. However, every visitor of the site should have a separate instance of the context, not work on one big "site-wide" instance. I guess this reduces the possibilites to have an instance lifetime only for the current request.
As UnityConfig.RegisterComponents() is in the Application_Start() method, I guess it would only create one instance for the entire application.
What is the best practice in this case? I have thought about the following:
Create my own factory for the DbContext which returns a singleton, and inject this factory into my repositories
Move UnityConfig.RegisterComponents() to Application_BeginRequest()
I tried to search for InjectionFactory on Microsoft's site, not much luck (http://msdn.microsoft.com/en-us/library/microsoft.practices.unity.injectionfactory%28v=pandp.51%29.aspx)
What best practice should I follow in this case? I don't want to overengineer it, what is the simplest working solution?
I'm not a web developer but reading through the book Dependency Injection With Unity they did mention a special lifetime manager that you can use for a single HTTP request - PerRequestLifetimeManager
Perhaps that would work for your needs?
Remove the factory and replace with:
container.RegisterType<ApplicationDbContext>(new HierarchicalLifetimeManager());
This will result in an ApplicationDbContext instance per request and also take call of disposing of the context at the end of the request.
I think what you're after is the unit of work pattern.
Take a look at the following link
http://www.asp.net/mvc/tutorials/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application

EF6 (code first), MVC, Unity, and a service layer without a repository

My application is using SQL Server 2012, EF6, MVC and Web API.
It's also using a repository and assorted files such as:
DatabaseFactory.cs
Disposable.cs
IDatabaseFactory.cs
IRepository.cs
IUnitOfWork.cs
RepositoryBase.cs
UnitOfWork.cs
We already use a service layer between our controllers and the repository
for some complicated business logic. We have no plans EVER to change to a different database and it has been pointed
out to me that the recent thinking is that EF6 is a repository so why build
another repository on top of it and why have all of the files I have above.
I am starting to think this is a sensible approach.
Does anyone know of any examples out there that implement EF6 without a
repository, with a service layer. My search on the web has revealed many
complex code examples that seem over complicated for no reason at all.
My problem is also when using a Service Layer then where do I put:
context = new EFDbContext()
In the controller, the service layer or both ? I read that I can do this with dependancy injection. I already use Unity as an IOC but I don't know how I can do this.
Entity Framework IS already a Unit of Work pattern implementation as well as a generic repository implementation (DbContext is the UoW and DbSet is the Generic Repository). And I agree that it's way overkill in most apps to engineer another UoW or Generic Repository on top of them (besides, GenericRepsitory is considered to be an anti-pattern by some).
A Service layer can act as a concrete repository, which has a lot of benefits of encapsulating data logic that is specific to your business needs. If using this, then there is little need to build a repository on top of it (unless you want to be able to change your backend service technology, say from WCF to WebApi or whatever..)
I would put all your data access in your service layer. Don't do data access in your controller. That's leaking your data layer into your UI layer, and that's just poor design. It violates many of the core SOLID concepts.
But you do NOT need an additional UnitOfWork, or other layers beyond that in most cases, unless your apps are very complex and intended to work in multiple environments...
Setting up Unity for ASP.NET MVC and WebAPI is quite easy if you install and add the Unity.Mvc* and Unity.WebAPI* Nuget packages to your project. (The * is a version number, like 3 or 4 or 5. Look for the appropriate versions for your project. Here are for example the links to the Unity.Mvc 5 package and to the Untity.WebAPI 5 package.)
The usage of these packages is explained in this blog post.
The building blocks are roughly like so:
You build a unity container and register all your dependencies there, especially the EF context:
private static IUnityContainer BuildContainer()
{
var container = new UnityContainer();
container.RegisterType<MyContext>(new HierarchicalLifetimeManager());
container.RegisterType<IOrderService, OrderService>();
container.RegisterType<ICustomerService, CustomerService>();
container.RegisterType<IEmailMessenger, EmailMessenger>();
// etc., etc.
return container;
}
MyContext is your derived DbContext class. Registering the context with the HierarchicalLifetimeManager is very important because it will ensure that a new context per web request will be instantiated and disposed by the container at the end of each request.
If you don't have interfaces for your services but just concrete classes you can remove the lines above that register the interfaces. If a service needs to be injected into a controller Unity will just create an instance of your concrete service class.
Once you have built the container you can register it as dependency resolver for MVC and WebAPI in Application_Start in global.asax:
protected void Application_Start()
{
var container = ...BuildContainer();
// MVC
DependencyResolver.SetResolver(
new Unity.MvcX.UnityDependencyResolver(container));
// WebAPI
GlobalConfiguration.Configuration.DependencyResolver =
new Unity.WebApiX.UnityDependencyResolver(container);
}
Once the DependencyResolvers are set the framework is able to instantiate controllers that take parameters in their constructor if the parameters can be resolved with the registered types. For example, you can create a CustomerController now that gets a CustomerService and an EmailMessenger injected:
public class CustomerController : Controller
{
private readonly ICustomerService _customerService;
private readonly IEmailMessenger _emailMessenger;
public CustomerController(
ICustomerService customerService,
IEmailMessenger emailMessenger)
{
_customerService = customerService;
_emailMessenger = emailMessenger;
}
// now you can interact with _customerService and _emailMessenger
// in your controller actions
}
The same applies to derived ApiControllers for WebAPI.
The services can take a dependency on the context instance to interact with Entity Framework, like so:
public class CustomerService // : ICustomerService
{
private readonly MyContext _myContext;
public CustomerService(MyContext myContext)
{
_myContext = myContext;
}
// now you can interact with _myContext in your service methods
}
When the MVC/WebAPI framework instantiates a controller it will inject the registered service instances and resolve their own dependencies as well, i.e. inject the registered context into the service constructor. All services you will inject into the controllers will receive the same context instance during a single request.
With this setup you usually don't need a context = new MyContext() nor a context.Dispose() as the IOC container will manage the context lifetime.
If you aren't using a repository then I assume you would have some place to write your logic/processing that your service operation would use. I would create a new instance of the Context in that logic/process class method and use its methods directly. Finally, dispose it off right after its use probably under a "using".
The processing method would eventually transform the returned/processed data into a data/message contract which the service returns to the controller.
Keep the data logic completely separate from Controller. Also keep the view model separate from data contract.
If you move ahead with this architecture, you are going to be tightly coupling the Entity Framework with either your service or your controller. The repository abstraction gives you a couple things:
1) You are able to easily swap out data access technologies in the future
2) You are able to mock out your data store, allowing you to easily unit test your data access code
You are wondering where to put your EF context. One of the benefits of using the Entity Framework is that all operations on it are enrolled into a transaction. You need to ensure that any data access code uses the same context to enjoy this benefit.
The design pattern that solves that problem is the Unit of Work pattern, which by the looks of things, you are already using. I strongly recommend continuing to use it. Otherwise, you will need to initialize your context in your controller, pass it to your service, which will need to pass it to any other service it interacts with.
Looking at the objects you have listed, it appears to be a considerate attempt to build this app with enterprise architectural best practices. While abstractions do introduce complexity, there is no doubting the benefit they provide.

DbContext per HTTP Request But Avoid Dependency on HttpContext in Data Layer

I've been thinking of how I could use one instance of a DbContext per HttpRequest in a layered application. One of the solutions I came up with would be to create an HttpModule that would initialize an instance of the context in HttpContext.Current.Items in the BeginRequest event handler and then dispose it in the EndRequest event handler.
The approach above poses a problem though: I need to reference System.Web in my data layer and business layer in order to get a hold of the stored DbContext instance. This is probably okay but I prefer to avoid going that route. What if I wanted to reference and use my data layer and business layers from a non-web application?
Any ideas?
You can use dependency injection. Simply create interface IContextHolder with method to get a context and inject the instance into your lower layer from the web application. The implementation of this interface will be different for different types of applications - it will wrap the access to the real storage for your context instance.
One of the simplest solutions would be to wrap the access to the data context in a static property in a facade/gateway class.
This way, in a web application, the property could access the HttpContext.Current.Items and store the context there. On the other hand, if the http context is missing, you could implement any other lifetime management policy for a non-web application.
public static TheDbContext Current {
get {
if ( HttpContext.Current != null ) {
// lifetime management for a web app
// e.g. with the Items container
}
else {
// lifetime management for a non-web app
}
}
}
The facade itself doesn't have to be a part of the data layer, you don't then reference System.Web in a data layer.

How do I get a service to start from global.asax without having to invoke it?

I have a simple app where I use global.asax to map a serviceroute to a wcf service through a custom servicehostfactory in Application_Start. The constructor of that service does some initial processing to set up the service which takes a bit of time.
I need this constructor to fire when its serviceroute is added automatically. I tried creating a clientchannel from global.asax and making a dummy call to spin up the service, but discovered the service isn't up yet -- it seems application_start has to return?
So how do I get the constructor of the service to fire when first mapped through global.asax without having to manually hit the service? Unfortunately AppFabric isn't an option for us, so I can't just use it's built-in autostart..
UPDATE
I was asked for a bit more detail;
This is like a routing management service. So I have Service1 -- it gets added as a serviceroute in global.asax. Now I have http://localhost/Service1
Inside Service1 I have a method called 'addServiceRoute'. When called, it also registers a route for Service2. Now I have http://localhost/Service1/Service2.
My initial solution from global.asax was to build a channelfactory to http://localhost/service1 but that wouldn't work. Service1 wasn't up yet and wouldn't come up till Application_Start returned (Still not sure why?). So then I thought I'd cheat and move that initial addserviceroute call to the constructor of service1. Also didn't work.
It was mentioned that this shouldnt be in the constructor -- i agree, this is just testing code.
A singleton was also mentioned, which might be ok, but I intend to have more than one instance of Service1 on a machine (in the same app pool) so I don't think that'll work?
** UPDATE #2 **
I was asked for sample code.. here it is from global.asax (trimmed a bit for brevity).. So http://localhost/Test DOES come up.. But if I have to use appfabric to warm up Test and get its constructor to fire, then don't I need Test.svc or something? How do I get appfabric to even see this service exists?
protected void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.Ignore("{resource}.axd/{*pathInfo}");
RouteTable.Routes.Add(
new ServiceRoute("Test", new MyServiceHostFactory(ITestService, BindingType.BasicHttpBinding, true), TestService));
}
What you describe requires singleton service (something you should avoid) because normally each call or session gets a new instance = a new call to constructor. In self hosted WCF service you can instantiate singleton service instance and pass it to ServiceHost constructor. In case of IIS hosted service used together with ServiceRoute you can try to create your own class derived from ServiceHostFactory and pass created service instance as a parameter to its constructor. In this factory class implement CreateServiceHost method and pass that existing service instance into ServiceHost constructor. To make this work your service class must still be handled as singleton through service behavior.
Btw. constructor should not do any time consuming operation. Constructor is for constructing object not for initializing infrastructure. Using constructor for such initialization is bad practice in the first place.
AppFabric autostart is what I would recommend - even though you say you cannot use it - this is the problem it was meant to solve (warming up your service).
As an alternative before AppFabric existed, you would have to use a scheduled task (a.k.a cron job) with an executable that calls into the service you want initialized. The way AppFabric autostart works is by using named pipes (net.pipe) to trigger the warm up - but it just does this exact thing when the service is recycled. The difference between the scheduled task approach and the AppFabric autostart is that the scheduled task doesn't know when your application pool has been recycled - you would need to poll your service periodically to keep it warm.
Alternatively you could consider hosting your WCF application outside of IIS via self-hosting. This would avoid the warm-up issue, but you wouldn't achieve many of the benefits of the IIS hosted container. See HttpSelfHostServer in the new MVC Web API or review using a standard ServiceHost.

Resources