4

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?

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Nice.. this is exactly what I want to do. Thanks!
0

You can do this. It's possible. It will only create the Session Id once (which is what I'd assume you'd want to do.)

I would personally rather give the DummyProxy a dependency on the DummySession (or better yet, an abstraction like IDummyProxy) and make it call DummySession.GetSessionID().

2 Comments

Well, I actually need the SessionId be called every time, so each resolve for DummyProxy will have new SessionId.
I could modify DummyProxy to depend on IDummySession, but I thought there might be a simpler way to do this..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.