Factory method and Dependency injection, Some services are not able to be constructed

Viewed 25

I'm trying to use Factory method in my app, when i try to inject them it throws an exception.

public abstract class TransferFactory
{
    protected abstract ITransfer MakeTransfer();
    public ITransfer CreateTransfer() => MakeTransfer();
}

public class CsvTransferFactory:TransferFactory
{
    private readonly CsvTransfer _csvTransfer;

    public CsvTransferFactory(CsvTransfer csvTransfer)
    {
        _csvTransfer = csvTransfer;
    }

    protected override ITransfer MakeTransfer()
    {
        ITransfer transfer = _csvTransfer;
        return transfer;
    }
}
public class CsvTransfer:ITransfer
{
    private readonly IProductCategoryRepository _productCategoryRepository;
    
    public CsvTransfer(IProductCategoryRepository productCategoryRepository)
    {
        _productCategoryRepository = productCategoryRepository;
    }

    public async Task<HttpResponseMessage> ExecuteTransfer(TransferTypeEnum transferType,List<string> assetCategoryIds,List<Guid> categoryIds)
    {
        //removed for brevity
    }
}

startup.cs
services.AddTransient<IProductCategoryRepository, ProductCategoryRepository>();
services.AddTransient<CsvTransferFactory>();

I get the following error:

Error while validating the service descriptor 'ServiceType: app.Co re.Interfaces.ITransferService Lifetime: Transient ImplementationType: app.Core.DomainServices.TransferService': Unable to resolve service for type 'app.Core.DomainServices.TransferServices.ConcreteTransfers.CsvTransfer' while attempting to activate 'app.Core. DomainServices.TransferServices.ConcreteTransfers.CsvTransferFactory'

1 Answers

As exception hints - you need to register CsvTransfer too:

services.AddTransient<IProductCategoryRepository, ProductCategoryRepository>();
services.AddTransient<CsvTransfer>();
services.AddTransient<CsvTransferFactory>();

Though I would say that more common approach is to use factory methods when you want to manually instantiate the classes and not manage them via DI (though there is at least one use case for such approach - keyed dependencies).

Related