统一的自动工厂使用参数 [英] Unity auto-factory with params

查看:144
本文介绍了统一的自动工厂使用参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出注入一个自动的工厂,需要PARAMS,或者即使这是可能的团结的正确方法。

I'm trying to figure out the correct way to inject an auto-factory which takes params, or even if this is possible with Unity.

例如,我知道我能做到这一点:

For example I know I can do this:

public class TestLog
{
     private Func<ILog> logFactory;

     public TestLog(Func<ILog> logFactory)
     {
          this.logFactory = logFactory;
     }
     public ILog CreateLog()
     {
         return logFactory();
     }
}

Container.RegisterType<ILog, Log>();
TestLog test = Container.Resolve<TestLog>();
ILog log = test.CreateLog();

现在我就希望能够做的是:

Now what I'll like to be able to do is:

public class TestLog
{
     private Func<string, ILog> logFactory;

     public TestLog(Func<string, ILog> logFactory)
     {
          this.logFactory = logFactory;
     }
     public ILog CreateLog(string name)
     {
         return logFactory(name);
     }
}

Container.RegisterType<ILog, Log>();
TestLog test = Container.Resolve<TestLog>();
ILog log = test.CreateLog("Test Name");

可惜,这是行不通的。我可以看到你如何设置自定义为工厂创造统一的情况下,似乎无法资助这个例子任何明确的例子。

Unfortunately this doesn't work. I can see how you can set up custom factories for creating instances in Unity, just can't seem to fund any clear examples for this example.

显然我可以创建自己的工厂,但我在寻找一种优雅的方式在Unity与最低code做到这一点。

Obviously I could create my own factory but I'm looking for an elegant way to do this in Unity and with minimum code.

推荐答案

对不起,是那些讨厌的人谁回答自己的问题之一,但我想它了。

Sorry to be one of those annoying people who answer their own questions but I figured it out.

public class TestLog
{
    private Func<string, ILog> logFactory;

    public TestLog(Func<string, ILog> logFactory)
    {
         this.logFactory = logFactory;
    }
    public ILog CreateLog(string name)
    {
        return logFactory(name);
    }
}

Container.RegisterType<Func<string, ILog>>(
     new InjectionFactory(c => 
        new Func<string, ILog>(name => new Log(name))
     ));

TestLog test = Container.Resolve<TestLog>();
ILog log = test.CreateLog("Test Name");

这篇关于统一的自动工厂使用参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆