3 回答
TA贡献1802条经验 获得超6个赞
这是一个与其他答案不同的解决方案,希望能解决您对容器特殊用途的担忧:
namespace AutofacTest
{
public interface IServiceA { }
public interface IServiceB { }
public class ServiceA : IServiceA
{
}
public class ServiceB : IServiceB
{
private readonly IServiceA _serviceA;
public ServiceB (IServiceA serviceA)
{
_serviceA = serviceA;
}
}
public class MyConsumer
{
private readonly IServiceA _serviceA;
private readonly IServiceB _serviceB;
public MyConsumer(Func<IServiceA> serviceAFactory, Func<IServiceA, IServiceB> serviceBFactory)
{
_serviceA = serviceAFactory();
_serviceB = serviceBFactory(_serviceA);
}
}
}
在这个解决方案中,我注入工厂而不是实例,然后调用它们来获取实例。这个实现有点难看的一件事是参数顺序现在很重要。
如果你真的不希望顺序很重要,你可以IServiceA在IServiceB接口上公开一个 setter ,然后用类似的东西替换构造函数
public MyConsumer(Func<IServiceA> serviceAFactory, Func<IServiceB> serviceBFactory)
{
_serviceA = serviceAFactory();
_serviceB = serviceBFactory(_serviceA);
_serviceB.SetServiceA(_serviceA);
}
- 3 回答
- 0 关注
- 154 浏览
添加回答
举报