我刚刚阅读了 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/