PostSharp中的依赖注入



我刚刚阅读了有关从目标对象导入依赖项的 PostSharp.net 文档,需要从WCF服务的角度进行一些澄清。

这是我修剪的缓存方面,我正在尝试通过 Unity 使用 ICache

[Serializable]
public class CacheAspect : OnMethodBoundaryAspect, IInstanceScopedAspect
{
    [IntroduceMember(Visibility = Visibility.Family, OverrideAction = MemberOverrideAction.Ignore)]
    [CopyCustomAttributes(typeof(ImportAttribute))]
    [Import(typeof(ICache))]
    public ICache Cache { get; set; }
    [ImportMember("Cache", IsRequired = true)] 
    public Property<ICache> CacheProperty;
    public override void OnEntry(MethodExecutionArgs args)
    {
        var cache = this.CacheProperty.Get();            
    }        
    object IInstanceScopedAspect.CreateInstance(AdviceArgs adviceArgs)
    {
        return this.MemberwiseClone();
    }
    void IInstanceScopedAspect.RuntimeInitializeInstance()
    {
        var container = new UnityContainer();
        container.LoadConfiguration();
        var distributedCache = container.Resolve<DistributedCache>();
        this.CacheProperty.Set(distributedCache);
    }
}

我的问题是RuntimeInitializeInstance方法。

我想知道在此方法中设置 CacheProperty 是正确的方法还是应该以不同的方式进行?

[RuntimeInitializeInstance] 方法中初始化ICache依赖项是正确的方法之一,但提供的实现效率不高,因为每次都会创建和配置新的容器实例。

通常,让 DI 容器为你解析依赖项比手动设置依赖项更方便。

[IntroduceMember]属性告诉 PostSharp 将Cache属性直接添加到服务类中。在运行时解析服务实例时,Unity 容器可以自动设置此Cache属性。

您可以通过使用 [Dependency] 属性(为属性

注入注释对象)来指示 Unity 设置属性值。要将此属性复制到服务类,还需要应用 [CopyCustomAttributes] 属性。

[IntroduceMember(Visibility = Visibility.Family, OverrideAction = MemberOverrideAction.Ignore)]
[CopyCustomAttributes(typeof(DependencyAttribute))]
[Dependency]
public ICache Cache { get; set; }

示例中的属性是从文档中复制的,并演示了 MEF 容器的相同原则。