EF核心使用通用工厂注册数据库上下文

时间:2019-04-28 08:34:34

标签: c# generics asp.net-core dependency-injection entity-framework-core

我为此出海。

我收到了answer并由Nkosi更正的here。.虽然它指出了如何重写工厂,但我不愿意执行该工厂的任务。.我需要填补一些空白

据我了解,这是我需要做的。

定义接口:

public interface IContextFactory<TContext> where TContext : DbContext 
{
    TContext Create(string connectionString);
}

创建工厂:

public class ContextFactory<TContext> : IContextFactory<TContext>
    where TContext : DbContext
{
    public TContext Create(DbContextOptions<TContext> options)
    {
        return (TContext)Activator.CreateInstance(typeof(TContext), options);
    }
}

在启动时将工厂注册为单例。

这是我所做的,我不知道这是否正确吗?

services.AddSingleton(typeof(IContextFactory<>), typeof(ContextFactory<>));

接下来,我该如何使用这个工厂?

在第一个答案中,有人建议我使用它:

public class EntityBaseRepository<T> : IEntityBaseRepository<T> where T : class, IEntityBase, new()
{
    private JobsLedgerAPIContext _context;

    public string ConnectionString { get; set; }

    public EntityBaseRepository(IContextFactory<JobsLedgerAPIContext> factory)
    {
        _context = factory.CreateDbContext(ConnectionString);
    }

    public virtual IQueryable<T> GetAll()
    {
        return _context.Set<T>().AsQueryable();
    }

    public virtual int Count()
    {
        return _context.Set<T>().Count();
    }
}

Nkosi确定您不能具有约束“ new()”和参数化构造函数。他重写了它。我该如何更改上面的代码,以反映工厂现在没有参数化构造函数,但在给定Nkosi工厂的情况下仍采用连接字符串的事实?

ClientRepository继承了上述内容。

public class ClientRepository : EntityBaseRepository<Client>, IClientRepository
{
    private new JobsLedgerAPIContext _context;

    public ClientRepository(JobsLedgerAPIContext context) : base(context)
    {
        _context = context;
    }

是否需要更改此构造函数。

最后,既然我必须提供一个连接字符串,我该如何注入ClientRepository?

0 个答案:

没有答案