Reputation: 1
I have the following class hierarchy where I have a base interface (IBase) and a base implementation of it and derived interfaces (IExtended) that inherit from the base one, extend it and have their own concrete implementations.
public interface IBase
{
void Execute();
}
public abstract class BaseImplementation : IBase
{
public virtual void Execute() {
Console.WriteLine("BaseImplementation: Executing base functionality.");
}
}
public interface IExtended1 : IBase
{
void ExtendedFunctionality1();
}
public class ExtendedImplementation1 : BaseImplementation, IExtended1
{
public void ExtendedFunctionality1()
{
Console.WriteLine("ExtendedImplementation1: Executing extended functionality 1.");
}
public override void Execute()
{
base.Execute();
Console.WriteLine("ExtendedImplementation1: Overridden base execution.");
}
}
public interface IExtended2 : IBase
{
void ExtendedFunctionality2();
}
public class ExtendedImplementation2 : BaseImplementation, IExtended2
{
public void ExtendedFunctionality2()
{
Console.WriteLine("ExtendedImplementation2: Executing extended functionality 2.");
}
public override void Execute()
{
base.Execute();
Console.WriteLine("ExtendedImplementation2: Overridden base execution.");
}
}
I want to add a cross cut functionality via a decorator that applies to the base interface and all of its implementations. The decorator would be something like the below:
public class BaseDecorator : IBase
{
private readonly IBase _inner;
public BaseDecorator(IBase inner) {
_inner = inner;
}
public void Execute() {
Console.WriteLine("BaseDecorator: Before execution.");
_inner.Execute();
Console.WriteLine("BaseDecorator: After execution.");
}
}
I want the consumers of the extended interfaces to request an IExtended as dependency and be able to resolve to a concrete implementation that is decorated by the BaseDecorator. A consumer is a class that requires the IExtended interface as dependency in its constructor.
Also, I don't want to create separate decorators for the implementation of each new IExtendedX that I add in the system.
Is it possible to do such DI binding using Autofac or my design is wrong here?
I tried various DI bindings using Autofac but none worked. I think the fundamental reason is that Autofac resolves services in composition scenarios and not in inheritance. However, there must be a solution to my problem since this seems a quite common one.
Upvotes: 0
Views: 40
Reputation: 9481
Dependency injection generally has a difficult relationship with inheritance-based injection. Staying compositional will generally make your life significantly better when dealing with IOC containers. For what you are trying to do, you will be better off with an AOP-oriented approach like Interceptors. This will allow you to layer functional on top of the functions (like decorators), as opposed to IOC oriented approaches which are really meant to replace internal functionality, not top-level.
Upvotes: 0