Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity - Inject an object to Constructor by calling a Method of a Class

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?

like image 424
stack247 Avatar asked Mar 18 '23 22:03

stack247


1 Answers

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.

like image 185
Lukazoid Avatar answered Apr 08 '23 08:04

Lukazoid