如何从IRouter访问存储库

时间:2018-01-16 14:57:26

标签: entity-framework-core aspnetboilerplate

我正在开发模块化应用程序,我希望来自不同模块的实体能够注册自己友好的url slugs。

app.UseMvc(routes =>
{
    routes.Routes.Add(new SlugRouter(routes.DefaultHandler));
    (...)
});

但是下面的代码抛出无法访问已处置的对象。对象名称:' CommerceDbContext'。,当尝试从存储库访问slug时。

public class SlugRouter : IRouter
{
    private readonly IRouter _target;

    public SlugRouter(IRouter target)
    {
        _target = target;
    }

    public async Task RouteAsync(RouteContext context)
    {
        var slugRepository = context.HttpContext.RequestServices.GetService<IRepository<SlugEntity>>();

        // ERROR: Cannot access a disposed object. Object name: 'CommerceDbContext'
        var urlSlug = await slugRepository.GetAllIncluding(x => x.EntityType).FirstOrDefaultAsync(x => x.Slug == context.HttpContext.Request.Path.Value);
        (...)
    }       

为了能够从路由器访问存储库,我一定很简单。谢谢你的帮助。

2 个答案:

答案 0 :(得分:1)

开始unit of work

public async Task RouteAsync(RouteContext context)
{
    var slugRepository = context.HttpContext.RequestServices.GetService<IRepository<SlugEntity>>();
    var unitOfWorkManager = context.HttpContext.RequestServices.GetService<IUnitOfWorkManager>();

    using (var uow = unitOfWorkManager.Begin())
    {
        var urlSlug = await slugRepository.GetAllIncluding(x => x.EntityType).FirstOrDefaultAsync(x => x.Slug == context.HttpContext.Request.Path.Value);
        await uow.CompleteAsync();
    }
}

答案 1 :(得分:0)

访问IModel。您不需要dbContext for。

  

来自不同模块的实体能够注册自己的   友好的url slugs

我是这样做的:

1)将OnModelCreating移动到静态methiod

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        BuildModel(modelBuilder);
    }

    public static void BuildModel(ModelBuilder modelBuilder)
    {
        // ...
    }

2)根据需要创建模型:

        var conventionSet = new ConventionSet();
        var modelBuilder = new ModelBuilder(conventionSet);
        AdminkaDbContext.BuildModel(modelBuilder);
        var mutableModel = modelBuilder.Model; 

有你的meta(在mutableModel中)。您可以遍历实体(实体类型)。