c# - WindowsForm 中具有 UnitOfWork 和 Repository 模式的 DI 使用 Autofac
问题描述
我在构建项目 WindowsForm 应用程序依赖注入时遇到问题。这是我在 Program.cs 文件中的代码。
var builder = new ContainerBuilder();
builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly());
// Register your Web API controllers.
//builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder.RegisterType<UnitOfWork>().As<IUnitOfWork>().InstancePerRequest();
builder.RegisterType<DbFactory>().As<IDbFactory>().InstancePerRequest();
builder.RegisterType<DITestDbContext>().AsSelf().InstancePerRequest();
//builder.Register(c => app.GetDataProtectionProvider()).InstancePerRequest();
// Repositories
builder.RegisterAssemblyTypes(typeof(ProductCategoryRepository).Assembly)
.Where(t => t.Name.EndsWith("Repository"))
.AsImplementedInterfaces().InstancePerRequest();
// Services
builder.RegisterAssemblyTypes(typeof(ProductCategoryService).Assembly)
.Where(t => t.Name.EndsWith("Service"))
.AsImplementedInterfaces().InstancePerRequest();
Autofac.IContainer container = builder.Build();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(container.Resolve<Form1>());
`
这是我在 Form1.cs 中的代码
private IProductCategoryService productCategoryService;
private IUnitOfWork unitOfWork;
public Form1(IProductCategoryService productCategoryService, IUnitOfWork unitOfWork)
{
this.productCategoryService = productCategoryService;
this.unitOfWork = unitOfWork;
InitializeComponent();
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
LoadProductCategory();
}
private void LoadProductCategory()
{
var data = productCategoryService.GetAll();
gridControl1.DataSource = data;
}
我得到了错误
DependencyResolutionException:无法解析类型“DITest.Service.ProductCategoryService”,因为无法找到它所属的生命周期范围。此注册公开了以下服务: - DITest.Service.IProductCategoryService'
我想我在启动 Form1 时犯了一个错误。任何人都可以帮助我吗?谢谢!
解决方案
您收到此错误是因为您InstancePerRequest
在 Windows 窗体应用程序中使用。
InstancePerRequest
旨在由 Web 应用程序使用,它允许每个 Web 请求有一个实例。
为了使您的应用程序正常工作,只需删除InstancePerRequest
. 如果未指定范围,Autofac 将使用范围。InstancePerDependency
您可以在文档中找到有关范围的更多信息:实例范围
推荐阅读
- c# - C#工厂异步套接字错误“主机断开连接”
- javascript - 在 WordPress 网站中使用 AJAX 传入 sessionStorage 数据
- macos - CoreGraphics:如果图像被缩放,绘制 NSImage 的性能会受到影响
- java - 在 Java 上的一个线程中等待多个事件
- r - R将两个列表合并为一个,从每个列表中交替绘制元素
- r - dplyr:评估名称在向量中的变量的总和
- ios - NSURLSession 完成处理程序意味着如果 didReceiveChallenge 被自动调用
- java - Spring批处理分区,多个步骤按顺序运行?
- html - 着色父菜单点
- c# - 尝试从 Cosmos DB 中删除时找不到资源