Reputation: 1388
I follow official guide to use simple injector to inject object in web form and it works, but now i cant make it works in custon control
this is what i do:
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);
}
}
}
but i get null reference exception since iuow
is null
i try to edit global.asax to manage UserControl in this way:
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;
}
}
but i get same error
is this doable?
Upvotes: 0
Views: 348
Reputation: 172666
To be able to get this working, you will have to hook onto the PreLoad
event of the page during initialization. During PreLoad
you can walk the page's control hierarchy and initialize all controls like you do with the page itself.
There's actually example code in the Simple Injector repository (that never made it to an official package) that shows you how to do this. Take a look here.
Upvotes: 1