大多数在线示例都与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();
但是我得到了这个错误
违反了
继承安全规则的类型:'System.Net.Http.WebRequestHandler‘。派生类型必须要么与基类型的安全可访问性匹配,要么不可访问。
因为实际的MessageController.cs
在Post
上创建了一个新的作用域,所以它甚至更加复杂
using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, activity))
{
var dialog = scope.Resolve<IDialog<object>>();
await Conversation.SendAsync(activity, () => dialog);
}
如何进行注册?
编辑:按照建议,使用InstancePerRequest
解决了问题。但是我也有一个每X秒运行一次的Quartz作业,它也需要一个存储库。
builder.RegisterType<DealJob>()
.AsSelf()
.SingleInstance();
无法解析类型“”BargainBot.Repositories.MyContext“”,因为找不到它所属的生存期范围。“”此注册公开了以下服务:- BargainBot.Repositories.MyContext
详细信息->在请求实例的作用域中看不到标记与'AutofacWebRequest‘匹配的作用域。如果您在web应用程序的执行过程中看到此消息,则通常表示SingleInstance()正在请求注册为per-HTTP请求的组件
此时,我是否应该手动解析新的DbContext?或者我应该改变我的repo的生命周期?
Edit2:看起来我仍然得到这个错误,即使在删除整个Quartz作业注册。
发布于 2017-03-05 08:30:46
我错了,这不是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>
发布于 2018-06-01 04:40:56
我遇到了类似的问题,经过多次的反复,下面的代码对我来说是有效的:
DbContext
public class SalesDbContext : DbContext
{
public SalesDbContext(DbContextOptions<SalesDbContext> options) : base(options)
{
}
public DbSet<Domain.Product.Product> Products { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
// Configure database attributes
}
}
存储库
public class ProductRepository : IProductRepository
{
private readonly SalesDbContext _db;
public ProductRepository(SalesDbContext db)
{
_db = db;
}
}
Autofac模块
public class DefaultModule : Module
{
protected override void Load(ContainerBuilder builder)
{
// Register Entity Framework
var dbContextOptionsBuilder = new DbContextOptionsBuilder<SalesDbContext>().UseSqlServer("MyConnectionString");
builder.RegisterType<SalesDbContext>()
.WithParameter("options", dbContextOptionsBuilder.Options)
.InstancePerLifetimeScope();
}
}
发布于 2017-03-26 20:40:47
安装System.Net.Http 4.3.1解决了我的问题
https://stackoverflow.com/questions/42602458
复制相似问题