2016-06-22 2 views
0

私はWebフォームでオブジェクトを注入する簡単な注射器を使用するofficial guideに従うと、それは動作しますが、今私は、これは私が何をすべきかですcuston制御にシンプルインジェクタ

を作品作りカント:

public partial class GestioneAttivita_cnStruttureSocieta : System.Web.UI.UserControl 
{ 
    [Import] 
    public IUnitOfWork iuow { get; set; } 

    public Domain.Entity.Attivita attivitaGestita {get; set;} 

    protected void Page_Load(object sender, EventArgs e) 
    { 
     using (iuow) 
     {  
      attivitaGestita = iuow.Attivita.Read(attivitaGestita.IdAttivita); 
     } 
    } 

}

しかしiuowがnull

である私が男にGlobal.asaxのを編集しようとするので、私はnull参照の例外を取得このように年齢のUserControl:

private static void RegisterWebPages(Container container) 
     { 
      var pageTypes = 
       from assembly in BuildManager.GetReferencedAssemblies().Cast<Assembly>() 
       where !assembly.IsDynamic 
       where !assembly.GlobalAssemblyCache 
       from type in assembly.GetExportedTypes() 
       where (type.IsSubclassOf(typeof(Page)) **|| type.IsSubclassOf(typeof(UserControl)))**      
       where !type.IsAbstract && !type.IsGenericType 
       select type; 

      foreach (Type type in pageTypes) 
      { 
       var registration = Lifestyle.Transient.CreateRegistration(type, container); 
       registration.SuppressDiagnosticWarning(
        DiagnosticType.DisposableTransientComponent, 
        "ASP.NET creates and disposes page classes for us."); 
       container.AddRegistration(type, registration); 
      } 
     } 
    } 

     class ImportAttributePropertySelectionBehavior : IPropertySelectionBehavior { 
      public bool SelectProperty(Type serviceType, PropertyInfo propertyInfo) { 
       // Makes use of the System.ComponentModel.Composition assembly 

       bool _return = false; 

       _return = (typeof(Page).IsAssignableFrom(serviceType) && 
        propertyInfo.GetCustomAttributes<ImportAttribute>().Any()) 
        **|| 
        (typeof(UserControl).IsAssignableFrom(serviceType) && 
        propertyInfo.GetCustomAttributes<ImportAttribute>().Any());** 

       return _return; 
      } 
     } 

しかし、私は

このなんとかです同じエラーが出ますか?

答えて

1

この機能を利用できるようにするには、初期化中にページのPreLoadイベントにフックする必要があります。 PreLoadの間、ページのコントロール階層を歩き回り、ページ自体のようにすべてのコントロールを初期化することができます。

実際に、これを行う方法を示すSimple Injectorリポジトリ(公式パッケージには決して書かれていない)のコード例があります。見てくださいhere

+0

私はそのコードを見ましたが、どこに置く必要がありますか? 私はそれが単純なインジェクタライブラリの一部であると正直に考えていました... –

+0

@ gt.guybrush:統合パッケージWebフォームはありません。そのため、代わりにWebフォームと統合する方法を文書化しました。このコードを書き換えて面白い部分をコピーする必要があります(たとえば、マスターページの初期化は必要ありません)。私はあなたが[回線132](https://github.com/simpleinjector/SimpleInjector/blob/master/src/SimpleInjector.Integration.Web.WebForms/SimpleInjectorWebFormsHttpModule.cs#L132)(および関連コード)を呼び出さなければならないと言いますあなたが現在 'Global.InitializeHandler(ハンドラ) 'と呼ぶところで。しかし、コードをちょっと微調整する必要があります。 – Steven

+0

かなり完全にすべてのコードをコピーするが、私はSetContainerを呼び出す必要がありますので、それがnullであり、エラーを与える読み取りする必要はありません。それは私にとっては非常に複雑すぎている...ユーザーコントロールの管理を主張するautofacを試すことを考えている –

関連する問題