Currently I have a simple generic abstract class with one service parameter in constructor which is resolved by dependency injection.
public abstract class CosmosCommandHandler<T>
{
protected readonly ICosmosStore<T> _cosmosStore;
protected CosmosCommandHandler(ICosmosStore<T> cosmosStore)
{
_cosmosStore = cosmosStore;
}
}
and some concrete class inheriting from it
public class FooCommandHandler : CosmosCommandHandler<Foo>
{
private readonly IFooService _fooService;
public FooCommandHandler(ICosmosStore<Foo> cosmosStore, IFooService fooService)
: base(cosmosStore)
{
_fooService = fooService;
}
}
This is all fine, but I want to add a new service to abstract class and resolve it with DI as well. My idea is that I should use constructor chaining for this, but it's not working out. Something like this.
public abstract class CosmosCommandHandler<T>
{
private readonly IAuditService _auditService;
protected readonly ICosmosStore<T> _cosmosStore;
private CosmosCommandHandler(ICosmosStore<T> cosmosStore, IAuditService auditService)
{
_cosmosStore = cosmosStore;
_auditService = auditService;
}
protected CosmosCommandHandler(ICosmosStore<T> cosmosStore)
: this(cosmosStore, IAuditService auditService)
{
}
}
Obviously I could just pass the IAuditService
from FooCommandHandler
just like ICosmosStore
, but that doesn't seem right as FooCommandHandler
has nothing to do with IAuditService
. It is out of its scope.
Is this possible to achieve?
If IAuditService
is out of the FooCommandHandler
scope, then create child of your CosmosCommandHandler
class which will have that IAuditService
. And that child also could be abstract class. Also, you could create additional overloaded constructor for your CosmosCommandHandler
class - and that FooCommandHandler
class does not need to use it. But that also breaks the concept of inheritance because FooCommandHandler
class has nothing to do with IAuditService
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.