首页 新闻 赞助 找找看

.net core3 依赖注入 异常问题

0
悬赏园豆:20 [待解决问题]

.net core 3 放开上面蓝色部分正常运行,但是注释上面改成自动注入就会报错了,不知道问题是在哪里

〤‵坠落者...的主页 〤‵坠落者... | 初学一级 | 园豆:8
提问于:2020-10-16 18:25
< >
分享
所有回答(4)
0

参考 Implement dynamic dependency injection in ASP.NET Core 2.2, example with multitenancy scenario

namespace WebApiDemo.Extensions
{
    public static class ServiceCollectionExtensions
    {
        public static void AddScopedDynamic<TInterface>(this IServiceCollection services, IEnumerable<Type> types)
        {
            services.AddScoped<Func<string, TInterface>>(serviceProvider => tenant =>
            {
                var type = types.FilterByInterface<TInterface>()
                                .Where(x => x.Name.Contains(tenant))
                                .FirstOrDefault();

                if (null == type)
                    throw new KeyNotFoundException("No instance found for the given tenant.");

                return (TInterface)serviceProvider.GetService(type);
            });
        }
    }
}
dudu | 园豆:31075 (高人七级) | 2020-10-17 09:39
0

这种注入代码看起来不太优雅啊 推荐通过反射批量注入,代码更加简洁

.NET Core 跨平台实战

智客工坊 | 园豆:1855 (小虾三级) | 2020-10-19 13:24
0
拉克斯文 | 园豆:356 (菜鸟二级) | 2020-10-19 16:22
0

1.你的DBContext在哪注入的?
2.依照你的代码,批量注入时 BaseRespository<> 也没有注入进来啊

gt1987 | 园豆:1150 (小虾三级) | 2020-10-20 13:38
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册