Use autofac in multiple projects

I have a great wpf application. I simplify my problem with autofac. Say I have a ViewModelLocator where I create a skin. ViewModelLocator is located in the Company.WPF project, this project belongs to the Company.ViewModels project.

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

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

How can I configure Autofac for them? I usually use castel Wisndor, is there a setting for this situation, a similar option in Autofac too?

+5
source share
1 answer

You are looking for the concept of Modules in autofac. For each level of your architecture, you add a new autofac module for that level, where you register the types of this layer. In ViewModelLocator , where you create your autofac container, you simply register autofac modules, rather than register all types directly.

In more detail, and for your case, it may look something like this:

In the Company.Services project:

You add a new ServicesModule module 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 the project Company.ViewModels :

You also create a ViewModelModule where you register all of 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 the project Company.Wpf ( ViewModelLocator ):

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

Note that since we registered the ServiceModule within the ViewModelModule , we just need to register the ViewModelModule directly in the ContainerBuilder . This has the advantage that you do not need to add a link to the Company.Service project as part of the Company.Wpf project.

+5
source

Source: https://habr.com/ru/post/1242481/


All Articles