小编Nat*_*obs的帖子

使用 ApplyConfigurationsFromAssembly() 程序集扫描时访问 IEntityTypeConfiguration<T> 内的 DI 服务

我需要访问 IEntityTypeConfiguration 类中的一些 DI 服务,以便找到一些用户会话信息并执行一些查询过滤。

我可以通过执行以下操作以“手动”方式实现这一点......

    // setup config to use injection (everything normal here)
    public class MyEntityConfig: IEntityTypeConfiguration<MyEntity>
    {
        private readonly IService _service;

        public MyEntityConfig(IService service)
        {
            IService = service;
        }


        public void Configure(EntityTypeBuilder<MyEntity> entity)
        {
            // do some stuff to entity here using injected _service
        }
    }

    //use my normal DI (autofac) to inject into my context, then manually inject into config
    public class MyContext: DbContext
    {
        private readonly IService _service;

        public MyContext(DbContextOptions options, IService service) : base(options) …
Run Code Online (Sandbox Code Playgroud)

c# dependency-injection autofac entity-framework-core

5
推荐指数
1
解决办法
642
查看次数