li-raz
li-raz

Reputation: 1696

Unity WebApi container is created every time

i am creating a simple web service using web api MVC 4, i am using Unity web api as my IOC, how ever in the documentation it said to add it to the application_start

protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        Bootstrapper.Initialise();

        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }

which means that for every request it is created

public static void Initialise()
    {
        _container = BuildUnityContainer();

        GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(_container);
    }

    private static IUnityContainer BuildUnityContainer()
    {
        _container = new UnityContainer();
        // register all your components with the container here

        LoggingUtilities.LoadConfigFile("ThirdParty.log4net");
        ILog log = LoggingUtilities.DefaultLogger;
        _container.RegisterInstance<ILog>(log);

        log.InfoFormat("In BuildUnityContainer");
        OpClientWrapper wrapper = new OpClientWrapper(log);

        _container.RegisterInstance<OpClientWrapper>(wrapper, new ContainerControlledLifetimeManager());

        return _container;
    }

i want that my Opclient wrapper will be created only once for all requests , is it possible?

Upvotes: 1

Views: 368

Answers (1)

Fenton
Fenton

Reputation: 251102

Application_Start only fires once (see notes below) when the application starts - not per request.

Bear in mind that the following may cause the application to restart...

  • Thread pool restarts
  • Dropping new dlls into the bin folder
  • IIS Resets

So perhaps an application start was caused "while you were watching" that made it look like it was being called more often.

Upvotes: 1

Related Questions