asp.web中的简单注入器形成用户自定义控件

时间:2016-06-22 12:56:54

标签: c# asp.net dependency-injection simple-injector

我按照official guide使用简单的注入器以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;
            }
        }

但我得到同样的错误

这可行吗?

1 个答案:

答案 0 :(得分:1)

为了能够正常工作,您必须在初始化期间挂钩页面的PreLoad事件。在PreLoad期间,您可以浏览页面的控件层次结构并初始化所有控件,就像使用页面本身一样。

Simple Injector存储库中的实际示例代码(从未进入官方软件包)向您展示了如何执行此操作。看看here