簡體   English   中英

asp.web表單中的簡單注入器用戶自定義控件

[英]Simple injector in asp.web form user custom control

我遵循官方指南使用簡單的注入器以Web形式注入對象,並且它可以工作,但是現在我無法使其在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為空

我嘗試編輯global.asax以這種方式管理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;
            }
        }

但我得到同樣的錯誤

這可行嗎?

為了使此工作正常進行,您必須在初始化期間掛接到頁面的PreLoad事件。 PreLoad期間,您可以遍歷頁面的控件層次結構,並像對頁面本身一樣初始化所有控件。

實際上,Simple Injector存儲庫中有示例代碼(從未將其放入官方軟件包中)向您展示了如何執行此操作。 在這里看看。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM