首页 > 解决方案 > 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 时犯了一个错误。任何人都可以帮助我吗?谢谢!

标签: c#.netdependency-injectionautofac

解决方案


您收到此错误是因为您InstancePerRequest在 Windows 窗体应用程序中使用。 InstancePerRequest旨在由 Web 应用程序使用,它允许每个 Web 请求有一个实例。

为了使您的应用程序正常工作,只需删除InstancePerRequest. 如果未指定范围,Autofac 将使用范围。InstancePerDependency

您可以在文档中找到有关范围的更多信息:实例范围


推荐阅读