I have the following interface and its implementation
public class DummyProxy : IDummyProxy
{
public string SessionID { get; set; }
public DummyProxy(string sessionId)
{
SessionId = sessionId;
}
}
public interface IDummyProxy
{
}
Then I have another class to get a session id
public class DummySession
{
public string GetSessionId()
{
Random random = new Random();
return random.Next(0, 100).ToString();
}
}
Now, in my Unity container, I would like to inject 'session id' to DummyProxy every time the container is trying to resolve IDummyProxy. But this 'session id' must be generated from DummySession class.
container.RegisterType<IDummyProxy, DummyProxy>(
new InjectionConstructor(new DummySession().GetSessionId()));
Is this even possible?
Your best approach for this would be to make use of an InjectionFactory
, i.e.
container.RegisterType<IDummyProxy, DummyProxy>(new InjectionFactory(c =>
{
var session = c.Resolve<DummySession>() // Ideally this would be IDummySession
var sessionId = session.GetSessionId();
return new DummyProxy(sessionId);
}));
An InjectionFactory
allows you to execute additional code when creating the instance.
The c
is the IUnityContainer
being used to perform the resolve, we use this to resolve the session and then obtain the session id, from that you can then create your DummyProxy
instance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With