簡體   English   中英

AutoFac-如何使用參數注冊和解析對象?

[英]AutoFac - How to register and resolve an object with parameter?

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

據我了解的問題:

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

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

您不想每次實例化FooController都實例化DoSomethingElse類型。 您還希望在運行時為其提供一個值。

因此,這需要工廠模式:

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>()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM