Reputation: 2437
I have a situation where I would like to resolve a class with a dynamic constructor parameter in my ASP.NET 4, MVC web application. I am using Unity v4.0.1. I need the value that is passed to the constructor of the service on Resolve to be be different for each request as shown below.
var obj = new MyObject();
container.RegisterType<IMyService, MyService>(
new PerRequestLifetimeManager(),
new InjectionConstructor(obj));
How do I achieve this?
Upvotes: 1
Views: 1308
Reputation: 2437
I was able to achieve it as below by taking help from here.
Register my type as
container.RegisterType<IMyService, MyService>(new PerRequestLifetimeManager());
In my Global.asax.cs
protected void Application_BeginRequest()
{
var obj = new MyObject();
container
.Resolve<IMyService>(
new ParameterOverrides
{
{"obj", obj},
}.OnType<MyService>()
);
}
Make sure to have the constructor of MyService
as
public MyService(MyObject obj){
//do something here
}
Upvotes: 2