Use autofac in multiple project solution

我与影子孤独终老i 提交于 2019-12-21 04:51:40

问题


I have large wpf application. I simplify my problem with autofac. Let say I have ViewModelLocator where I create contrainer. ViewModelLocator is in Company.WPF project, this project refers Company.ViewModels project.

var builder = new ContainerBuilder();
builder.RegisterType<MainWindowViewModel>().AsSelf().SingleInstance();
container = builder.Build();

Problem: MainWindowViewModel needs ICompanyService (I use CI) which is in Company.Services project, this project should not be reference from Company.WPF. ICompanyService is public and in same project (Company.Services) is also implementation CompanyService, but it is only internal.

How can I setup Autofac for these? I normally use castel Wisndor, there are installers for these situation, is similar option in Autofac too?


回答1:


You are looking for the concept of Modules in autofac. For each layer in your architecture you add a new autofac module for that layer, where you register the types of that layer. In your ViewModelLocator, where you build your autofac container, you just register autofac modules instead of registering all types directly.

In more detail and for your case this could look something like this:

In your Company.Services project:

You add a new module ServicesModule with something like this. :

public class ServiceModule : Autofac.Module
{
  protected override void Load(ContainerBuilder builder)
  {
    // optional: chain ServiceModule with other modules for going deeper down in the architecture: 
    // builder.RegisterModule<DataModule>();

    builder.RegisterType<CompanyService>().As<ICompanyService>();
    // ... register more services for that layer
  }
}

In your Company.ViewModels project:

You also create a ViewModelModule where you register all your ViewModels similar to the ServiceModule.

public class ViewModelModule : Autofac.Module
{
  protected override void Load(ContainerBuilder builder)
  {
    // in your ViewModelModule we register the ServiceModule
    // because we are dependent on that module
    // and we do not want to register all modules in the container directly
    builder.RegisterModule<ServiceModule>();

    builder.RegisterType<MainViewModel>().AsSelf().InSingletonScope();
    // ... register more view models
  }
}

In your Company.Wpf project (ViewModelLocator):

var builder = new ContainerBuilder();
builder.RegisterModule<ViewModelModule>();
builder.Build();

Note that since we registered the ServiceModule within the ViewModelModule, we just have to register the ViewModelModule directly in the ContainerBuilder. This has the advantage of not needing to add a reference to the Company.Service project within the Company.Wpf project.



来源:https://stackoverflow.com/questions/35254557/use-autofac-in-multiple-project-solution

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!