2016-02-07 11 views
5

私は大きなwpfアプリケーションを持っています。私はautofacで私の問題を単純化します。私はContrainerを作成するViewModelLocatorを持っているとしましょう。 ViewModelLocatorはCompany.WPFプロジェクトにあり、このプロジェクトはCompany.ViewModelsプロジェクトを参照します。複数のプロジェクトソリューションでオートファクトを使用

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

問題:MainWindowViewModelはCompany.ServicesプロジェクトであるICompanyServiceを(私はCIを使用する)必要があり、このプロジェクトはCompany.WPFから参照すべきではありません。 ICompanyServiceは公開されており、同じプロジェクト(Company.Services)でもCompanyServiceが実装されていますが、内部的なものです。

これらのためにオートファックを設定するにはどうすればよいですか?私は通常、カステルWisndorを使用して、これらの状況のインストーラがありますが、Autofacでも同様のオプションですか?

答えて

5

あなたはModulesの概念をオートファックで探しています。アーキテクチャ内の各レイヤーに対して、そのレイヤーの新しいautofacモジュールを追加します。このモジュールでは、そのレイヤーのタイプを登録します。あなたのautofacコンテナを構築するViewModelLocatorでは、すべてのタイプを直接登録するのではなく、autofacモジュールを登録するだけです。あなたのCompany.Servicesプロジェクトで

より詳細には、あなたのケースのために、これは、このような何かを見ることができるあなたはこのようなもので、新しいモジュールを追加ServicesModule

。 :

あなた Company.ViewModelsプロジェクトで
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 
    } 
} 

:また、あなたはServiceModuleに似たすべてのあなたのviewmodelsを登録ViewModelModuleを作成

。我々はViewModelModuleServiceModuleを登録しているので、私達はちょうどContainerBuilderに直接ViewModelModuleを登録する必要があること

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

注:お使いのCompany.Wpfプロジェクト(ViewModelLocator)で

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 
    } 
} 

。これには、Company.Wpfプロジェクト内のCompany.Serviceプロジェクトへの参照を追加する必要がないという利点があります。

関連する問題