简体   繁体   中英

Fluent configurator/builder and IoC container

I'm about to create a fluent configurator/builder for my class when I realized I don't know how to use it together with my IoC container.

Let's say I create a class and a builder like this.

class MyClass
{
    private ILog _log;

    // here I want the ILog object from my container and configParameter1 from my builder.
    internal MyClass(ILog log, int configParameter1)
    {

    }
}

class MyClassBuilder
{
    private int _param1;
    private MyClassBuilder () {}

    public static MyClassBuilder Begin()
    {
        return new MyClassBuilder();
    }

    public MyClassBuilder SetParameter1(int param1)
    {
        _param1 = param1;
        return this;
    }

    public MyClass Build()
    {
        // Here I want to inject a ILog object from my container
        return new MyClass(?!?, _param1);
    }
}

The class MyClass depend on both types registered in my container and parameters from may builder. What is the best way to solve this? Should MyClassBuilder depend on ILog? If so I'm not able to use a static Begin method in the builder.

You could inject a factory into your MyClassBuilder :

class LogFactory
{

    public ILog CreateLogger(){

    }
}

Then you can ask this LogFactory to be injected into your builder:

class MyClassBuilder
{
    public MyClassBuilder(LogFactory factory)
    {
        _factory = factory;
    }

    // ... Builder methods

    public MyClass Build()
    {
        return new MyClass(_factory.CreateLogger(), _param1);
    }
}

您不能只是将ILog注入MyClass或使用像这样的方法:

private static ILog logger = LogManager.GetLogger(typeof(MyClass));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM