2011-07-06 4 views
0

このシナリオを動作させることは可能ですか?オートファックとオープンジェネリック

[TestFixture] 
    public class AutofacTests 
    { 
     private IContainer _container; 

     public AutofacTests() 
     { 
      var builder = new ContainerBuilder(); 

      builder.RegisterType<Command1>(); 
      builder.RegisterType<Command2>(); 

      builder.RegisterType<CommandHandler1>(); 
      builder.RegisterType<CommandHandler2>(); 

      builder.RegisterGeneric(typeof (IHandle<>)); 

      _container = builder.Build(); 
     } 

     [Test] 
     [Ignore] 
     public void Open_generics_test() 
     { 
      //this isn't working 
      CommandHandler1 commandHadler1 = _container.Resolve<IHandle<Command1>>(); 
      CommandHandler2 commandHadler2 = _container.Resolve<IHandle<Command2>>(); 
     } 

     interface IHandle<T> where T : class 
     { 
      void Handle(T command); 
     } 

     class CommandHandler1 : IHandle<Command1> 
     { 
      public void Handle(Command1 command) 
      { 
       throw new System.NotImplementedException(); 
      } 
     } 

     class Command1{} 

     class CommandHandler2 : IHandle<Command2> 
     { 
      public void Handle(Command2 command) 
      { 
       throw new System.NotImplementedException(); 
      } 
     } 

     class Command2{} 
    } 

答えて

2

私はRegisterGenericかなり確信している、例えばHandler<T>(オーバー閉じるために具体的な実装タイプを必要とします。私はあなたが持っているようにあなたは、インターフェイスを使用することができるとは思わない。

あなたはあなたが望むものを達成することができます次の代替の登録コード。

var builder = new ContainerBuilder(); 

builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()) 
    .AsClosedTypesOf(typeof(IHandle<>)); 

_container = builder.Build(); 

var commandHandler1 = _container.Resolve<IHandle<Command1>>(); 
var commandHandler2 = _container.Resolve<IHandle<Command2>>(); 

私はGitHubの上AutofacAnswersに、このの作業バージョンを追加した。

関連する問題