我想将myContext
传递给Business
和Facade
。在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;
}
答案 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; }
}