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.