2016-06-13 9 views
0

IDependencyResolverを使用して、コントローラにいくつかの依存関係を注入しようとしています。これは私のコントローラです。IDependencyResolver null例外

public class MyController: ApiController 
{ 
    private IMyService m_myService; 

    public MyController() 
    { 

    } 

    public MyController(IMyService myService) 
    { 
     m_myService = myService; 
    } 
    //Other code.... 
} 

私は内のすべての私のアプリの依存関係を持つカスタムサービス・プロバイダを使用していますし、私に提供し、それは必須使用されました。ここでは、使用しているserviceProviderを使用してIDependencyResolverを実装します。

WebApiを起動してNull例外が発生し、クラッシュすると問題が発生します。

Startup.cs 

public class Startup 
{ 
    //This property is being instantiated before calling configuration function 
    public static ServiceProvider ServiceProvider { get; set; } 

    public void Configuration(IAppBuilder application) 
    { 
     application.UseCors(CorsOptions.AllowAll); 
     HttpConfiguration configuration = new HttpConfiguration(); 
     configuration.DependencyResolver = new ServiceProviderResolver(ServiceProvider); 

     // Attribute routing. 
     configuration.MapHttpAttributeRoutes(); 

     application.UseWebApi(configuration); 

     configuration.EnsureInitialized(); 
    } 
} 

EDIT: 私はスタートアップクラスの内部UseWebApiメソッドを呼び出します。コードは、私のdependencyResolverのGetServiceメソッドを呼び出しており、パラメータによって渡されたTypeはIHostBufferPolicySelectorです。

ご協力いただければ幸いです。ありがとうございました!

+1

ここであなたはServiceProviderを割り当てていますか?また、例外の詳細を掲載してください(スタックトレースが含まれています)。 –

+0

こんにちは@FedericoDipuma私はちょうど3分前のようにそれを解決しました。ご関心をお寄せいただきありがとうございます! – acostela

答えて

0

私はちょうどそれを解決しました。問題は、GetServices(タイプserviceType)にありました。いくつかのケースではnullに戻りました。これを行う適切な方法は、nullを返して新しいリストを返す場合です。次のコードはそれを解決しました

public IEnumerable<object> GetServices(Type serviceType) 
{ 
    //Code is the same because our container only have an object for each Type 
    object result = null; 
    try 
    { 
     MethodInfo serviceProviderGetMethod = 
      m_serviceProvider.GetType().GetMethod("Get").MakeGenericMethod(new Type[] { serviceType }); 
     result = serviceProviderGetMethod.Invoke(m_serviceProvider, null); 
    } 
    catch (Exception) 
    { 

    } 

    if(resul == null) 
    { 
     return new List<object>(); 
    } 
    return (IEnumerable<object>) result; 
}