c# - PostSharp 中的依赖注入(inject)

标签 c# .net wcf unity-container postsharp

我刚刚阅读了 PostSharp.net 上关于 Importing Dependencies from the Target Object 的文档并且需要从 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] 属性 ( Annotating Objects for Property (Setter) Injection ) 注释来告诉 Unity 设置属性值。要将此属性复制到您的服务类,您还需要应用 [CopyCustomAttributes]属性。

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

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

关于c# - PostSharp 中的依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20926387/

相关文章:

c# - 反射 - 如何在参数的指定索引处获取值

.net - 从事件日志 .net 或 powershell 中识别第一个和最后一个事件

wcf - 服务操作需要交易才能流动

c# - Type.GetInterfaces() 仅用于声明的接口(interface)

c# - NAudio 演示不再有效

c# - 更快地释放注册表句柄

.net - 我可以从数据库项目初始化数据库吗?

c# - PLINQ AsParallel().ForAll() 访问资源

c# - 如何使用我的 InstanceProvider 使用自己的构造函数调用 WCF 服务

c# - 如何在 C# 中公开 WCF Web 服务调用响应 header