2016-02-07 34 views
0

您好,我是DI的新手,擁有統一性。我正在開發一個自定義屬性。在那個屬性中,我想在Unity的幫助下注入一個依賴項。但是,當在一個類中使用該屬性時,它會顯示異常。的代碼是:在自定義屬性中應用帶有Unity的DI

public interface ITest 
    { 
    } 
    public class AAttrib : Attribute 
    { 
     ITest _test; 
     public AAttrib(ITest test) 
     { 
      _test = test; 
     } 
    } 

    public class Test : ITest 
    { 
    } 

    [AAttrib] 
    public class Example 
    { 
     // to do 
    } 

的例外是:

沒有給定的參數對應於所需要的正式 參數的「AAttrib.AAttrib(ITEST) '測試'

public static void RegisterComponents() 
    { 
     var container = new UnityContainer(); 
     container.RegisterType<ITest, Test>(new HierarchicalLifetimeManager()); 
     GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container); 
    } 

Unity解析器類是:

public class UnityResolver: IDependencyResolver 
    { 
     protected IUnityContainer _container; 
     public UnityResolver(IUnityContainer container) 
     { 
      if(container == null) 
       throw new ArgumentNullException("container"); 

      this._container = container; 
     } 
     public void Dispose() 
     { 
      _container.Dispose(); 
     } 

     public object GetService(Type serviceType) 
     { 
      try 
      { 
       return _container.Resolve(serviceType); 
      } 
      catch (ResolutionFailedException r) 
      { 
       return null; 
      } 
     } 

     public IEnumerable<object> GetServices(Type serviceType) 
     { 
      try 
      { 
       return _container.ResolveAll(serviceType); 
      } 
      catch (ResolutionFailedException) 
      { 
       return new List<object>(); 
      } 

     } 

     public IDependencyScope BeginScope() 
     { 
      var child = _container.CreateChildContainer(); 
      return new UnityResolver(child); 
     } 
    } 
+0

考慮屬性注入而不是構造函數注入的依賴關係。 – tchelidze

+0

你能給我一個例子嗎 –

+0

不是通過構造函數初始化'_test',而是聲明屬性'[Dependency] ITest _test {get; set}',Unity會注入該屬性。 *注意:屬性上的'Dependency'屬性* – tchelidze

回答

1

你不能在屬性上使用依賴注入,因爲屬性是擴展類的元信息的Metainformation。而這些元信息是在編譯期間生成的