Jon Gear
Jon Gear

Reputation: 1018

Unity Parameter Injection with the InjectionConstructor

I would like to inject an object of type GraphClient into my MVC service classes at runtime. This object has a parameter of type Uri which is basically the Uri of the current tenant we wish to look at. Where I'm getting hungup is that this works perfectly for the initial load however as I switch to different tenants the uri persists with the first uri registered. Which makes sense. However I'm wondering, is there a way to tell Unity to do the parameter injection of this dependency at instantiation every time?

The following is a trimmed up version of my code.

var container = new UnityContainer();
container.RegisterType(typeof(GraphClient), new InjectionConstructor(RootUri));

protected static Uri RootUri
{
   get
   {
      SessionWrapper wrapper = new SessionWrapper();
      cString = wrapper.CurrentTenantUri;

      return new Uri(cString);
    }
}

Upvotes: 1

Views: 741

Answers (1)

TylerOhlsen
TylerOhlsen

Reputation: 5578

You can use an InjectionFactory to accomplish what you are after. This will get executed every time a GraphClient is needing to be instantiated.

container.RegisterType(typeof(GraphClient), 
                       new InjectionFactory(c => new GraphClient(RootUri)));

Upvotes: 1

Related Questions