[英]How do I register a Type in Autofac with a parameter and resolve it with parameters?
[英]How do I register a parameter for a DbContext with Autofac?
我正在使用实体框架和 Sql 来处理数据库。
我的上下文 class 是:
public class AnimalBreedsContext : DbContext
{
public DbSet<AnimalBreed> AnimalBreeds { get; set; }
public AnimalBreedsContext(DbContextOptions<AnimalBreedsContext> options) : base (options)
{
}
}
class AnimalBreeds 是一个 class 具有一些字符串属性,如名称等。
现在我想用 Autofac 注册 AnimalBreedsContext class。 我尝试过这样的事情:
class ContainerConfig
{
public static IContainer Configure()
{
var builder = new ContainerBuilder();
var options = new DbContextOptionsBuilder<AnimalBreedsContext>()
.UseSqlServer("configString")
.Options;
builder.RegisterType<AnimalBreedsContext>().WithParameter(options).AsSelf();
return builder.Build();
}
}
但问题是“参数选项无法从 AnimalBreedsContext 转换为 Autofac.Parameter”。
有没有其他选项可以让我用 Autofac 注册这个 class?
看起来您没有向 WithParameter 提供正确的WithParameter
。 这是显示所有重载的 Autofac 文档。
如果不将参数包装在一个 Autofac Parameter
对象中,看起来您可以提供参数的字符串名称作为第一个参数,然后提供实际参数 object 作为第二个参数:
builder.RegisterType<AnimalBreedsContext>()
.AsSelf()
.WithParameter("options", options);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.