Webforms MasterPages

Oct 1, 2014 at 11:00 PM
Hi,

Is it possible to use Simple Injector with MasterPages. I followed the guide:
https://simpleinjector.codeplex.com/wikipage?title=Web%20Forms%20Integration

and tried to make a BaseMasterPage class that the MasterPage inherites from. Further I added:

public static void Initialize(MasterPage masterPage)
{
    container.GetRegistration(masterPage.GetType().BaseType, true).Registration
        .InitializeInstance(masterPage);
}
to the Global.cs file but still I get 'System.NullReferenceException' when accessing the injected properties.

Is there a way to use MasterPage and UserControls in same way as for Page?

Would be thankful for an answer

/Haz
Coordinator
Oct 2, 2014 at 8:38 AM
By default, Simple Injector does not inject any properties as can be read here. To allow property injection you need to explicitly tell Simple Injector to do so, for instance by making the following registration:
var container = new Container();
container.Options.PropertySelectionBehavior = new ImportPropertySelectionBehavior();
The ImportPropertySelectionBehavior looks like this:
using System;
using System.ComponentModel.Composition;
using System.Linq;
using System.Reflection;
using SimpleInjector.Advanced;

class ImportPropertySelectionBehavior : IPropertySelectionBehavior {
    public bool SelectProperty(Type type, PropertyInfo prop) {
        return prop.GetCustomAttributes(typeof(ImportAttribute)).Any();
    }
}
Now you can mark your properties in your master page with the [System.ComponentModel.Composition.ImportAttribute] and you're done.
Oct 3, 2014 at 4:26 PM
Thanks you for your answer. I actually solved it with my Poor Man's DI. I didn't get your example to work.

It is strange that most of the DI Containers that are "supposed" to have support for Webforms actually only handles DI for Pages but don't have an easy way of for MasterPages and UserControls.
Coordinator
Oct 3, 2014 at 10:15 PM
The Simple Injector code base actually contains a Integrations.Web.Forms project that allows initializing user controls and master pages, but it never made it to a official release. But you can take a look at that to see how that works. And everything is published under the MIT license, which means you're free to copy and use.