[英]Inject a component property into another component's constructor parameter with Autofac
使用Autofac IoC容器,可以說有以下情形:
public interface IHaveASpecialProperty
{
SpecialType SpecialProperty { get; }
}
public class HaveASpecialPropertyImpl : IHaveASpecialProperty
{
// implementation
}
public class SomeComponent
{
public SomeComponent(SpecialType special)
{
_special = special;
// rest of construction
}
private readonly SpecialType _special;
// implementation: do something with _special
}
// in composition root:
containerBuilder.RegisterType<HaveASpecialPropertyImpl>
.As<IHaveASpecialProperty>();
containerBuilder.RegisterType<>(SomeComponent);
有沒有一種方法可以在Autofac容器中注冊HaveASpecialPropertyImpl
類型以充當SpecialType
實例的提供者/工廠?
我目前擁有的是這種經典方法:
public class SomeComponent
{
public SomeComponent(IHaveASpecialProperty specialProvider)
{
_special = specialProvider.SpecialProperty;
// rest of construction
}
private readonly SpecialType _special;
// implementation: do something with _special
}
基本原理基本上與Demeter定律有關: specialProvider
僅用於獲取SpecialType
實例,而后者是SomeComponent
所需和使用的實際依賴關系,因此,僅在不考慮SomeComponent
情況下注入SpecialType
實例似乎是合理的。實例來自。
PS:我讀過有關代表工廠的文章 ,不確定這是否是(唯一的)方法。
您可以注冊一個代表:
builder.Register(c => c.Resolve<IHaveASpecialProperty>().SpecialProperty)
.As<ISpecialType>();
使用此注冊,每次您解析ISpecialType
Autofac都會解析IHaveASpecialProperty
並將SpecialProperty
屬性值返回為ISpecialType
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.