使用参数进行Unity配置并立即创建实例

时间:2018-06-23 20:34:35

标签: c# .net inversion-of-control unity-container

我想将myContext传递给BusinessFacade。在Facade中。我想在参数中使用Business创建myContext的实例。

我收到此错误: Facade没有采用参数(MyContext)的构造函数。

我也尝试过类似的方法,但是不起作用:

public class Facade : IFacade
{
    readonly IBusiness business;
    readonly MyContext myContext;

    public Facade(MyContext context,IBusiness business)
    {
        this.myContext = context
        this.business = business;
    }
}

我当前的代码:

public class Facade : IFacade
{
    readonly IBusiness business;

    public Facade(IBusiness business)
        => this.business = business;
}

public class Business : IBusiness
{
    readonly Idal dal;

    public Business(IDal dal)
        => this.dal = dal;
}

public static IUnityContainer Init(MyContext myContext)
{
    IUnityContainer container = new UnityContainer();

    container.RegisterType<IFacade, Facade>
        (new TransientLifetimeManager(), new InjectionConstructor(myContext));

    container.RegisterType<IBusiness, Business>
        (new TransientLifetimeManager(), new InjectionConstructor(myContext));

    return container;
}

1 个答案:

答案 0 :(得分:0)

如果我的问题正确,那么您正在寻找这个

class Program
{
    static void Main(string[] args)
    {
        var context = new SomeClass() { SomeId = 10 };
        var container = ConfigureContainer(context);
        var facadeInstance = container.Resolve<IFacade>();
        Console.WriteLine(facadeInstance.ShowContextId());
    }

    public static IUnityContainer ConfigureContainer(SomeClass context)
    {
        IUnityContainer container = new UnityContainer();

        container.RegisterType<IFacade, Facade>(new TransientLifetimeManager(), new InjectionConstructor(new InjectionParameter(typeof(SomeClass), context)));

        return container;
    }
}

public interface IFacade
{
    int ShowContextId();
}

public class Facade : IFacade
{
    public readonly SomeClass _context;

    public Facade(SomeClass context)
    {
        _context = context;
    }

    public int ShowContextId() => _context?.SomeId ?? 0;
}

public class SomeClass
{
    public int SomeId { get; set; }
}