2013-03-16 11 views
9

私は単に依存関係を解決するためにAutoFacを使用しようとしていますが、それは要求されたサービス「ProductService」が登録されていないように要求されたサービスは登録されていません! AutoFac依存性注入

として例外がスローされます。

class Program 
{ 
    static void Main(string[] args) 
    { 
     var builder = new ContainerBuilder(); 

     builder.RegisterType<ProductService>().As<IProductService>(); 

     using (var container = builder.Build()) 
     { 
      container.Resolve<ProductService>().DoSomething(); 
     } 
    } 
} 

public class ProductService : IProductService 
{ 
    public void DoSomething() 
    { 
     Console.WriteLine("I do lots of things!!!"); 
    } 
} 

public interface IProductService 
{ 
    void DoSomething(); 
} 

私が間違ってやっている...この例外を回避するには、サービス を提供したりIsRegistered()を使用してコンポーネントを登録するには? Withステートメント

答えて

20

builder.RegisterType<ProductService>().As<IProductService>(); 

は、誰かがIProductServiceProductService

だからあなたがIProductServiceを解決する必要があり、それらを与える解決しようとするたびAutofacを語ったとProductServiceへ:

using (var container = builder.Build()) 
{ 
    container.Resolve<IProductService>().DoSomething(); 
} 

またはResolve<ProductService>をAsSelfに登録しておきたい場合:

builder.RegisterType<ProductService>().AsSelf(); 
+0

あなたは正しいと思われるが、NopCommerce氏が名前を挙げたオープンソースプロジェクトでAutoFacを初めて見たことがある。彼らはあなたに助言するリザーブアプローチを使っている。そして、それも働いていた。 たとえば、 builder.RegisterType ()。()。InstancePerHttpRequest(); builder.RegisterType ()。()。InstancePerHttpRequest(); builder.RegisterType 多分、彼らは私が見ることができなかった以上のことをしました。 –

+1

あなたのコメントの@RyuKaplan私は 'container.Resolve'の例は見ません...しかし、NopCommerceではAutofacの仕組みについて何も変更していないと思います。 Autofacを初めて使用する場合は、公式のドキュメント(https://code.google.com/p/autofac/wiki/GettingStarted – nemesv

+0

@nemesv)から始めてください。XServiceにIXServiceを実装した膨大な数のクローズがあります。たとえば、ProductServiceはIProductServiceを実装します。これらのタイプをすべて登録する方法。 – user960567

関連する問題