Question

I've just read the docs on PostSharp.net about Importing Dependencies from the Target Object and need some clarification from WCF service perspective.

This is my trimmed cache aspect in which I'm trying to use ICache via Unity:

[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);
    }
}

My issue is with the RuntimeInitializeInstance method.

I'd like to know if setting the CacheProperty in this method is the correct approach or should I be doing it differently ?

Was it helpful?

Solution

Initializing the ICache dependency in the [RuntimeInitializeInstance] method is one of the correct approaches, but the provided implementation is not efficient, because you create and configure a new container instance every time.

Usually, it's more convenient to let the DI container to resolve the dependencies for you instead of setting them manually.

The [IntroduceMember] attribute tells PostSharp to add the Cache property directly to your service class. When resolving the service instance during run-time, Unity container can set this Cache property for you automatically.

You can tell Unity to set the property value by annotating it with the [Dependency] attribute (Annotating Objects for Property (Setter) Injection). For this attribute to be copied to your service class you also need to apply the [CopyCustomAttributes] attribute.

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

The attributes in your example were copied from the documentation and demonstrate the same principle for the MEF container.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top