加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何在Repository中注入EntityFramework Core DbContext

发布时间:2020-12-15 22:42:28 所属栏目:百科 来源:网络整理
导读:大多数在线示例处理asp.net并将其DbContext注册为其启动服务注册表的一部分. 我尝试像这样注册我的DbContext builder.RegisterTypeMyContext() .AsMyContext() .InstancePerLifetimeScope();builder.RegisterTypeDealRepository() .KeyedIRepositoryDeal(Fib
大多数在线示例处理asp.net并将其DbContext注册为其启动服务注册表的一部分.

我尝试像这样注册我的DbContext

builder.RegisterType<MyContext>()
    .As<MyContext>()
    .InstancePerLifetimeScope();

builder.RegisterType<DealRepository>()
    .Keyed<IRepository<Deal>>(FiberModule.Key_DoNotSerialize)
    .As<IRepository<Deal>>()
    .SingleInstance();

builder.RegisterType<CardsDialog>()
    .As<IDialog<object>>()
    .InstancePerDependency();

但是我收到了这个错误

Inheritance security rules violated by type:
‘System.Net.Http.WebRequestHandler’. Derived types must either match
the security accessibility of the base type or be less accessible.

它更复杂,因为实际的MessageController.cs在Post上创建了一个新的范围

using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container,activity))
{
    var dialog = scope.Resolve<IDialog<object>>();

    await Conversation.SendAsync(activity,() => dialog);

}

如何进行注册?

编辑:
如建议的那样,使用InstancePerRequest解决了这个问题.但我也有一个Quartz作业,每X秒运行一次,也需要一个存储库.

builder.RegisterType<DealJob>()
    .AsSelf()
    .SingleInstance();

Unable to resolve the type ‘BargainBot.Repositories.MyContext’ because
the lifetime scope it belongs in can’t be located. The following
services are exposed by this registration:
– BargainBot.Repositories.MyContext

Details —> No scope with a tag matching ‘AutofacWebRequest’ is
visible from the scope in which the instance was requested. If you see this during execution of a web application,it generally indicates that a component registered as per-HTTP request is being requested by a SingleInstance()

我此时应手动解析新的DbContext吗?或许我应该改变我的回购生命周期?

Edit2:看起来即使删除整个Quartz作业注册,我仍然会收到此错误.

解决方法

我对这个问题错了,它不是IoC和DbContext问题.好像它是在.NET平台本身

https://github.com/dotnet/corefx/issues/9846#issuecomment-274707732

添加重定向就可以了

<dependentAssembly>
    <assemblyIdentity name="System.ComponentModel.TypeConverter" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.0.0" />
  </dependentAssembly>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读