AutoFac - 如何使用参数注册和解析对象?

时间:2016-07-21 09:01:30

标签: c# autofac autofac-configuration

public class FooController : ApiController
{
   private IDb db;
    public FooController (IDb context)
    {
        db = context;
    }

    public void DoSomething(string value)
    {
        var output = new DoSomethingElse(value);
    }
}

DoSomethingElse对象由此类中的几个方法使用,但并不是所有方法的必需条件。如何注册和解决DoSomethingElse

1 个答案:

答案 0 :(得分:2)

我理解的问题是:

public class FooController : ApiController
{
   private IDb db;
    public FooController (IDb context)
    {
        db = context;
    }

    public void DoSomething(string value)
    {
        var output = new DoSomethingElse(value);
    }
}

每次实例化DoSomethingElse时,都不希望实例化FooController类型。您还希望在运行时为其提供值。

所以这需要工厂模式:

public interface IDoSomethingElseFactory
{
    IDoSomethingElse Create(string value);
}

public class DoSomethingElseFactory : IDoSomethingElseFactory
{
    public IDoSomethingElse Create(string value)
    {
        // Every call to this method will create a new instance
        return new DoSomethingElse(value);
    }
}

public class FooController : ApiController
{
    private IDb db;
    private readonly IDoSomethingElseFactory doSomethingElseFactory;

    public FooController (
        IDb context,
        IDoSomethingElseFactory doSomethingElseFactory)
    {
        db = context;
        this.doSomethingElseFactory = doSomethingElseFactory;
    }

    public void DoSomething(string value)
    {
        // this will be the point at which a brand new
        // instance of `DoSomethingElse` will be created.
        var output = doSomethingElseFactory.Create(value);
    }
}

然后注册:

builder.RegisterType<DoSomethingElseFactory>()
       .As<IDoSomethingElseFactory>()