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

大多数在线示例处理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>
点赞