【问题标题】:Unity - Inject an object to Constructor by calling a Method of a ClassUnity - 通过调用类的方法将对象注入构造函数
【发布时间】:2014-07-26 00:58:30
【问题描述】:

我有以下接口及其实现

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

public interface IDummyProxy
{
}

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

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

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

container.RegisterType<IDummyProxy, DummyProxy>(
    new InjectionConstructor(new DummySession().GetSessionId()));

这可能吗?

【问题讨论】:

    标签: c# unity-container ioc-container


    【解决方案1】:

    您最好的方法是使用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);
    }));
    

    InjectionFactory 允许您在创建实例时执行附加代码。

    c 是用于执行解析的IUnityContainer,我们使用它来解析会话,然后获取会话 ID,然后您可以从中创建您的 DummyProxy 实例。

    【讨论】:

    • 很好..这正是我想做的。谢谢!
    【解决方案2】:

    你可以这样做。这是可能的。它只会创建一次 Session Id(这是我假设你想要做的。)

    我个人宁愿让 DummyProxy 依赖于 DummySession(或者更好的是,像 IDummyProxy 这样的抽象)并使其调用 DummySession.GetSessionID()。

    【讨论】:

    • 好吧,其实我每次都需要调用 SessionId,所以每次解析 DummyProxy 都会有新的 SessionId。
    • 我可以修改 DummyProxy 以依赖 IDummySession,但我认为可能有更简单的方法来做到这一点..
    猜你喜欢
    • 2017-03-12
    • 2018-12-12
    • 2020-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多