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));
}
}
}
As the error says : as per constraint, compiler is expecting
BlogPostContextwith parameter less constructor. Adding below parameter less constructor toBlogPostContextshould resolve the errorAs an additional note: To me it looks like you need to inject other dependencies as well into
BlogPostContext, so why defineT : new()constraint in first place. Shouldn't you be injecting the concrete implementation for other constructor parameters as well in your start up.