Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception when registering UnityPerRequestHttpModule with MVC 5

I use Unity3 with MVC5, and need per request life time manager. However, when I launch the web app, I got server error saying "Cannot register a module after the application has been initialized." The problem is caused by the DynamicModuleUtility. How to solve this problem?

public static void Start()
{
    var container = UnityConfig.GetConfiguredContainer();

    FilterProviders.Providers.Remove(FilterProviders.Providers.OfType<FilterAttributeFilterProvider>().First());
    FilterProviders.Providers.Add(new UnityFilterAttributeFilterProvider(container));
    DependencyResolver.SetResolver(new UnityDependencyResolver(container));

    //use per request life time manager
    DynamicModuleUtility.RegisterModule(typeof(UnityPerRequestHttpModule));
}
like image 215
Bargitta Avatar asked Jul 17 '14 01:07

Bargitta


2 Answers

I had the same problem. My problem was this:

In the GlobalAsax.Application_Start() method I had written.

UnityMvcActivator.Start();

When I removed it, everything worked. When you use the UnityMvcActivator class, the Start method is already called through the annotation:

[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(TrackingServer.App_Start.UnityWebActivator), "Start")]

So you don't need to call the UnityMvcActivator methods in the Global.asax file again.

like image 191
elif Avatar answered Oct 11 '22 11:10

elif


For MVC, you want to put this in a class in the App_Start folder. If you add unity for MVC as a nuget package, I think it should create a class called UnityMvcActivator in that folder.

like image 27
Jim Avatar answered Oct 11 '22 11:10

Jim