Unity - 通过调用类的方法将对象注入到构造函数中

sta*_*247 4 c# ioc-container unity-container

我有以下界面及其实现

public class DummyProxy : IDummyProxy
{
    public string SessionID { get; set; }
    public DummyProxy(string sessionId)
    {
        SessionId = sessionId;
    }
}

public interface IDummyProxy
{
}
Run Code Online (Sandbox Code Playgroud)

然后我有另一个类来获取会话ID

public class DummySession
{
    public string GetSessionId()
    {
        Random random = new Random();
        return random.Next(0, 100).ToString();
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,在我的Unity容器中,每次容器尝试解析IDummyProxy时,我都想向DummyProxy注入'session id'.但是这个'session id'必须从DummySession类生成.

container.RegisterType<IDummyProxy, DummyProxy>(
    new InjectionConstructor(new DummySession().GetSessionId()));
Run Code Online (Sandbox Code Playgroud)

这甚至可能吗?

Luk*_*oid 7

对此最好的方法是使用a InjectionFactory,即

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);
}));
Run Code Online (Sandbox Code Playgroud)

An InjectionFactory允许您在创建实例时执行其他代码.

cIUnityContainer用于执行解析的,我们使用它来解析会话,然后获取会话ID,然后您可以创建您的DummyProxy实例.