Use MEF like any other DI container

Dec 12, 2009 at 11:27 PM

 

Hi, is it possible to simply use MEF as a standard DI container that will resolve it's dependencies in something like a bootstrapper?

I'd like to use it with jQuery ajax calls; the server side methods will have to be static and have therefore no access to any resolved properties in  the codebehind (pls correct if incorrect).

 

So I was thinking of having a helper class (and this works, but is ugly as hell) in which I do something like:

public class MessageProvider
{
    public MessageProvider()
    {
        var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
        new CompositionContainer(catalog).ComposeParts(this);
    }

    [ImportMany(typeof(ICustomMessage))]
    public IEnumerable<ICustomMessage> Messages { get; set; }
}

where the implementation in the codebehind would be something like:
[WebMethod]
public static string StaticMessage
{
    get
    {
        var messages = new MessageProvider().Messages;
        if (messages != null)
        {
            return messages.First().GetDetails();
        }
        return "doesn't work...";

    }
}
Now is totally contrived example but I wonder if there's a way around explicitly wiring up the helper class each time I need it.