我有一个类,我尝试在我的StartUp.cs
文件中创建依赖注入,就像这样
services.AddTransient<IContextFactory<BlogPostContext>, ContextFactory<BlogPostContext>>();
我也尝试将 the 传递给这样IContextFactory
的构造函数
public BlogPostRepository(IContextFactory<BlogPostContext> blogPostContext)
但我在上面的行中收到错误说明
“BlogPostContext”必须是具有公共无参数构造函数的非抽象类型,以便在泛型类型或方法“IContextFactory”中将其用作参数“T”
我不知道为什么,因为我new T()
在接口声明中用作约束。
这是我要实例化的类
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);
}
}
通用接口及其具体实现
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));
}
}
}