Using the Unity.Mvc3 with a Mvc 3 application, i could register my IDummyService as follows:
container.RegisterType<IDummyService, DummyService>(new HierarchicalLifetimeManager());
On each web request, a new instance of my IDummyService is created (as explained in this article), but since I upgraded Mvc 3 to Mvc 4 and hense Unity.Mvc3 to Unity.Mvc, an single instance is created and used across all web requests, untill restarting the app. Basically, IDummyService is a singleton in a Mvc 4 application when using HierarchicalLifetimeManager. For me this is hard to believe this is intended new behavior in Unity.Mvc.
Is there a better explanations for this?
Unity.Mvc3 and Unity.Mvc are created by two different organizations and have different implementations.
Unity.Mvc3 creates a child container per web request. This works well with the built-in HierarchicalLifetimeManager.
Unity.Mvc does not create a child container, but instead chose to create a new LifetimeManager called PerRequestLifetimeManager.
Related
Working on an MVC application with the below architecture. Bootstrapped with Castle Windsor.
Controller -> Service -> Repository (uses DbContext).
Now certain flows in the application require that I run some part of the flow in a thread.
For example:
Controller -> service ->Repo1 -> control returns to service -> new
Thread() started-> Repo2
The issue I face is the dbcontext is disposed as it is declared as LifestylePerWebRequest().I have tried using LifestyleTransient() that didnt seem to work. What am I missing?
There are similar dependencies which i have to sometimes use in a separate thread and sometimes in a single request. How do i configure Windsor to handle these dependencies?
There is a nuget package that i use to extend the lifestyles for Castle Windsor and it is called: Castle.Windsor.Lifestyles.
It has hybrid lifestyles which are handy for web requests and threads.
container.Register
(
Classes.FromAssemblyContaining<IServiceFactory>()
.BasedOn<IServiceFactory>()
.WithServiceAllInterfaces()
.Configure(c => c.LifeStyle.HybridPerWebRequestPerThread())
);
The important functionality is HybridPerWebRequestPerThread() which creates a new instance for the initial web request and then for every new thread it will create a new instance.
In the new ASP.NET 5.0 (vNext), the startup code relies on the IApplicationBuilder interface. The Use method is used to add a handler to the builder, while Build is used to construct the final delegate. But I can't figure out what is the purpose of New. I've been digging in GitHub, but can't find any place where that's used.
Anyone understand what is the purpose of that method?
New() creates a second ApplicationBuilder, sharing all the ApplicationServices and ServerFeatures of the first one, but none of the middleware. It is used internally by the branching extensions (Map, MapWhen, UseWhen) to create the new 'branch'.
You can find the implementation here: ApplicationBuilder.cs.
In some cases, it is also useful in higher-level frameworks.
For exemple, the [MiddlewareFilter] attribute in MVC Core uses New() internally to execute a piece of ASP.NET Core middleware inside the MVC framework (i.e. as a filter). MVC Core creates a small pipeline around the middleware, builds it into a RequestDelegate, then runs the HttpContext through it. Just like ASP.NET Core does with your 'main' pipeline built in Startup.cs.
Thanks to this feature, we can reuse a piece of general-purpose ASP.NET Core middleware, from inside MVC.
For more information, see MiddlewareFilterBuilder.cs in ASP.NET MVC Core.
It appears to be there to branch [clone] the original instance (as can be demonstrated in src/Microsoft.AspNet.Http/Extensions/MapExtensions.cs). There was also a previous MapWhenExtensions.cs, but it appears to have been removed from the dev branch.)
I suspect it's an artifact of a previous design that would provide the ability to bind middleware based on circumstances without affecting the root's configuration. The fact that it's been there since before IBuilder was refactored to IApplicationBuilder and that most dependencies were in files that have since been removed from the dev branch, I would venture a guess that it's old news.
Of course it's hard to tell given neither the interface nor the base implementation are commented.
I've set up Unity for dependency injection for our project. The project itself is an ASP.NET application that uses both MVC and Web API.
For the database context, I'm using the PerRequestLifetimeManager. This is done so that the different bits of business logic are using the same context (and thus the same transaction).
In order to be able to use the PerRequestLifetimeManager, I've added references to the nuget packages Unity bootstrapper for ASP.NET MVC and Unity bootstrapper for ASP.NET Web API.
For use of this lifetime manager in Web API, the following line has been added to the startup code:
Microsoft.Web.Infrastructure.DynamicModuleHelper.DynamicModuleUtility.RegisterModule(typeof(UnityPerRequestHttpModule));
The Unity container is set up for both MVC and Web API:
var container = BuildUnityContainer();
GlobalConfiguration.Configuration.DependencyResolver = new Microsoft.Practices.Unity.WebApi.UnityDependencyResolver(container);
System.Web.Mvc.DependencyResolver.SetResolver(new Microsoft.Practices.Unity.Mvc.UnityDependencyResolver(container));
In building the Unity container, the database context is set up to be resolved per request in the following way:
container.RegisterType<IDataContext>(new PerRequestLifetimeManager(),
new InjectionFactory(c =>
{
// Some code
return new DataContext(/* params */);
}
));
However, it seems that this code is not giving me a new DataContext for each request. It is giving me the same context in different places within a single request (which is fine). However, subsequent (web api) requests are being given the same instance of DataContext where I would expect a new one to be created for each new request. I also would expect the DataContext to be properly disposed of after the request is finished (the class implements IDisposable).
What's going on here? Am I missing a bit of configuration to make this work properly? Or isn't this supposed to work the way I expect it to?
The problem turned out to be that the UnityDependencyResolver was caching the resolved items over several requests. I had to change it to the UnityHierarchicalDependencyResolver and then it started resolving my items properly according to the associated LifetimeManager. The problem initially became more confusing when it appeared that even when using a TransientLifetimeManager, it would still return the same instance.
I found the answer in a different (yet somewhat related) question: using a Handler in Web API and having Unity resolve per request
So all I did was change
GlobalConfiguration.Configuration.DependencyResolver = new Microsoft.Practices.Unity.WebApi.UnityDependencyResolver(container);
to
GlobalConfiguration.Configuration.DependencyResolver = new Microsoft.Practices.Unity.WebApi.UnityHierarchicalDependencyResolver(container);
and all my problems were solved.
I'm new to MVC. I created a ASP.NET MVC5 Login project (UI) using Razor engine that is authentication responsible by using OWIN (VS2013). ViewModels and Data for solution are separated and layered by DLL. I would like to create two separated MVC5 project (UI) into same solution, each one is like a subsystem (eg: Accounting project, Inventory project, etc). Always user has to pass authentication project (Login) first and then according its necessity navigate to Accounting or Inventory subsystem.
My goal is that I could add or remove subsystems when deploying according company negotiation that let it use one or any subsystem.
How can I achieve that?
Every subsystem must be created using a separated ASP.NET MVC5 project template or can be created by a separated DLL?
You can use areas. See http://www.codeguru.com/csharp/.net/net_asp/mvc/article.php/c20227/Using-Areas-in-ASPNET-MVC-Application.htm
What are Areas?
Areas are functionally independent modules of your ASP.NET MVC application that mimic the folder structure and conventions of MVC. Consider the following scenario :
Problem
I have an ASP.NET MVC 3 application with the plug-in/module architecture and multi-tenancy support. MEF is used to resolve dependencies and load pluggable parts.
Each module consists of controllers, views, and other objects (phisically it's one assembly). Modules are loaded into tenants.
The simple configuration might look like this:
Tenant 1:
Module A, version 1.0 (ModuleA.dll)
Module B, version 1.0 (ModuleB.dll)
Tenant 2:
Module B, version 1.0 (ModuleB.dll)
Dll's for different modules and different versions are stored separately in different physical locations.
And application is running on one AppDomain (default one).
However, if we would like to do configuration where different tenants use different module versions, we encounter problem with loading the same assembly in different version. Which means that scenario below is not fully working because during resolving types from ModuleB we got composition mismatch exception (version 1.0 and 1.5 was loaded into MEF but only one assembly has been loaded into AppDomain by assembly loader).
Tenant 1:
Module A, version 1.0 (ModuleA.dll)
Module B, version 1.0 (ModuleB.dll)
Tenant 2:
Module A, version 1.5 (ModuleB.dll)
Solution?
So we came up with one solution, which is to load different tenants and theirs modules/assemblies into separate AppDomains. Meaning that from our example Tenant1 and Tenant2 are loaded into AppDomain1 and AppDomain2. In ASP.NET MVC pipeline we hooked up into controller factory in order to choose proper app domain, which would look like this:
Request is handled by default AppDomain (the one that web application started)
Controller factory
Takes Tenant_Id from the request and resolves proper controller from proper AppDomain (we have Tenant_Id->Tenant->AppDomain relation)
Returns ControllerProxy (which is a proxy class that implements IController and inherits MarshalByRefObject to be able to pass controller between different App Domians)
Action Invoker
Proper action is invoked on controller proxy object and right now execution takes place in underlying app domian
And here we bumped into problem because action invoker is not able to pass not serializable RequestContext to another app domain (in other words controllerProxy.Execute(RequestContext context) is throwing exception about serialization)
Question(s):
How to pass RequestContext (non serializable object) between app domains in a nice way?
Is it possible to hook up into another step in the pipeline to redirect execution to underlying app domain (before controller factory?)
Or any ideas about another solution for this problem?
Not possible. ASP.NET will come back and haunt you if you try to use different AppDomains.
Instead, use the role based authorization to control access for the different modules.
I've just written an article about plugin systems in ASP.NET MVC3: http://blog.gauffin.org/2012/05/griffin-mvccontrib-the-plugin-system/
This doesn't directly answer your question about multiple app domains within ASP.NET MVC. However, regarding other options, you might want to check out the Managed Application Framework (a.k.a. System.Addin). It is part of the .NET Framework, and is similar to MEF in that it supports dynamically loading modules. However, it has built in functionality for splitting those modules across app domains. It might be better suited to your needs. I'm not sure how well it fits with ASP.NET MVC, though.
This document on MSDN should get your started with MAF.