How can I solve my issue relating to parameterless constructor when using generics with constraint defined

267 Views Asked by At

I have a class that i try to create dependency injection for in my StartUp.cs file, like this

services.AddTransient<IContextFactory<BlogPostContext>, ContextFactory<BlogPostContext>>();

I also try to pass the the IContextFactory into a constructor like this

public BlogPostRepository(IContextFactory<BlogPostContext> blogPostContext)

but I get errors on the lines above stating that

'BlogPostContext' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'IContextFactory'

I am not sure why because I am using new T() as a constraint in my interface declaration.

Here is the class I am trying to instantiate

public class BlogPostContext
{
    private readonly IMongoDatabase _mongoDatabase;
    private readonly IMongoClient _mongoClient;

    public IMongoCollection<BlogPostModel> BlogPostModelCollection => _mongoDatabase.GetCollection<BlogPostModel>("BlogPostModel");

    public BlogPostContext(IMongoDatabase mongoDatabase, IOptions<MongoDbSettings> settings)
    {
        _mongoDatabase = mongoDatabase;
        _mongoClient = new MongoClient(settings.Value.ConnectionString);
        if (null != _mongoDatabase) _mongoDatabase = _mongoClient.GetDatabase(settings.Value.Database);
    }
} 

Generic interface and it's concrete implementation

namespace FloormindCore.Blog.Factory
{
    public interface IContextFactory<out T> where T : new()
    {
        T Create();
    }
}

using System;

namespace FloormindCore.Blog.Factory
{
    public class ContextFactory<T> : IContextFactory<T> where T : new()
    {
        public T Create()

        {
            return  (T)Activator.CreateInstance(typeof(T));
        }
    }
}
1

There are 1 best solutions below

0
rahulaga-msft On

As the error says : as per constraint, compiler is expecting BlogPostContext with parameter less constructor. Adding below parameter less constructor to BlogPostContext should resolve the error

public BlogPostContext(){} 

As an additional note: To me it looks like you need to inject other dependencies as well into BlogPostContext, so why define T : new() constraint in first place. Shouldn't you be injecting the concrete implementation for other constructor parameters as well in your start up.