0

Caliburn.Microの優れた紹介を読んだ後、私が見逃しているように見えることが 1 つあります。それは、引数を期待するコンストラクターにクラスを登録する方法です。

ここで問題の行は次のとおりです。

_container.PerRequest<IMobileServiceClient, MobileServiceClient>();

public class Bootstrapper : PhoneBootstrapper
{
    private PhoneContainer _container;

    protected override void Configure()
    {
        _container = new PhoneContainer();

        _container.RegisterPhoneServices(RootFrame);
        _container.PerRequest<MainPageViewModel>();
        _container.PerRequest<IRepository, Repository>();
        _container.PerRequest<IMobileServiceClient, MobileServiceClient>();
        AddCustomConventions();
    }

    //...
}   
4

2 に答える 2

1

ここで@floの回答を少し拡張します。

構築しようとしている具象型が、コンテナーに既に登録されているコンストラクターを介して型を受け入れる場合、Caliburn.Micro は、その型を作成しようとするときに必要なものを自動的に提供します。

たとえば、次のようなタイプのオブジェクトと別MyClassのタイプのオブジェクトを受け入れる名前付きの具象クラスがあるとします。IHellIHeaven

public class MyClass {
    public MyClass(IHell hell, IHeaven) { }
}

その後、あなたがする必要があるのは次のとおりです。

container.PerRequest<IHell, ConcreteHell>();
container.PerRequest(IHeaven, ConcreteHeaven>();

これで、Caliburn.Micro がそのインスタンスを作成しようとすると、コンテナーからMyClassプルされます。IHellIHeaven

問題に戻って、のMobileServiceClientようなコンストラクターを介してプリミティブ型のみを受け入れ、コンテナーに直接登録できない他の型のみを受け入れるようです。stringUri

この場合、次の 2 つのオプションがあります。

  1. などを作成するファクトリを作成しMobileServiceClient、それらをコンテナに登録し、インスタンスIMobileServiceClientFacotryMobileServiceClientFactoryImpl作成してそこで使用する必要があるタイプにそれらを注入しますMobileServiceClient

    これは、ソフトウェア エンジニアリングの観点からはより適切なソリューションですが、さらに 2 種類のオーバーヘッドが必要です。

  2. ファクトリをシミュレートするために使用されるHandlerメカニズムを使用して型を登録します。

    container.Handler<IMobileServiceClient>( iocContainer => new MobileServiceClient("http://serviceUrl.com:34"); );
    

    このソリューションは、大規模なアプリケーションで複雑すぎるファクトリーを必要としない場合に、より高速で適しています。

于 2013-11-02T13:15:05.627 に答える
0

PhoneContainer は IoC コンテナーとして機能します。これは、具体的なインスタンスの作成時にコンストラクターの依存関係が解決されることを意味します。

public class MobileServiceClient : IMobileServiceClient
{
 private IRepository _repository;

 // repository is resolved and injected by PhoneContainer 
 public MobileServiceClient (IRepository repository)
 {
  _repository = repository;
 }
}

ただし、注射の制御を維持する必要がある場合。LifetimeMode が異なる場合は、Bootstrapper でインスタンスを構成できます。

this.container.RegisterPerRequest(
                typeof(IMultiSelectionContext),
                null,
                new MobileServiceClient(new RepoXy()), null)));
于 2013-11-02T11:51:20.863 に答える