In my current project, I'm using quite a few Chain of Responsibility patterns.
However, I find it a bit awkward to configure the chain via dependency injection.
Given this model:
public interface IChainOfResponsibility
{
IChainOfResponsibility Next { get; }
void Handle(Foo foo);
}
public class HandlerOne : IChainOfResponsibility
{
private DbContext _dbContext;
public HandlerOne(IChainOfResponsibility next, DbContext dbContext)
{
Next = next;
_dbContext = dbContext;
}
public IChainOfResponsibility Next { get; }
public void Handle(Foo foo) { /*...*/}
}
public class HandlerTwo : IChainOfResponsibility
{
private DbContext _dbContext;
public HandlerTwo(IChainOfResponsibility next, DbContext dbContext)
{
Next = next;
_dbContext = dbContext;
}
public IChainOfResponsibility Next { get; }
public void Handle(Foo foo) { /*...*/}
}
My Startup becomes:
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IChainOfResponsibility>(x =>
new HandlerOne(x.GetRequiredService<HandlerTwo>(), x.GetRequiredService<DbContext>())
);
services.AddTransient(x =>
new HandlerTwo(null, x.GetRequiredService<DbContext>())
);
}
How to configure my chain of responsibility more cleanly?
Quick solution working for simplest cases of dependency chains.
and then
I've hacked a simple solution, as I couldn't find anything that did what I wanted. Seems to be working fine, as long as the
GetRequiredService
can resolve all constructor dependencies of all the handlers of the chain.My startup class becomes:
And the code that does the magic:
PS.: I'm answering my own question for future reference (myself and hopefully others), but I'd love some feedback on this.