1

我有一个类,我尝试在我的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));
        }
    }
}
4

1 回答 1

0

正如错误所说:根据约束,编译器期望BlogPostContext使用无参数构造函数。添加以下参数较少的构造函数BlogPostContext应该可以解决错误

public BlogPostContext(){} 

作为附加说明:对我来说,您似乎还需要将其他依赖项注入到BlogPostContext中,所以为什么要T : new()首先定义约束。您不应该在启动时也为其他构造函数参数注入具体实现吗?

于 2018-02-27T03:54:48.810 回答