views:

56

answers:

2

Hello. There are several examples of using MEF to plugin whole controller/view packages into a MVC application, but i didn't found one, using MEF to plugin funcional parts, used by other controllers.

For example, think of a NewsService with a simple interface like

interface INewsService
{
    List<NewsItem> GetAllNews();
}

That gets news wherever he wants, and returns them in a List of NewsItems. My page should load an exported INewsService and show the news on the page.

But there is the problem. I cant just use [Import] in the controllers, as they are just created when they are needed.

Edit: (Importing them to the main MVCApplication class doesn't work, becouse i cant access it from the controllers.) I think i found a way to access the main app via HttpContext.ApplicationInstance. But the Service object in this instance is null although it was created successfully in the Application_Start() method. Any idea why?

So, how can i access the NewsService from within a controller?

Thanks in advance, Marks

+1  A: 

I think this is the same as this question: http://stackoverflow.com/questions/760563/implementing-mef-with-asp-net-mvc

Anderson Imes
No its not. As written above I dont search for adding controllers and views like in your link. I search for adding plugin-services to existing controllers.
Marks
What's the difference? You still have to create a ControllerFactory, etc, and you have to have an Import on the Controller you create for the plugins to be hosted on. I don't see the distinction.
Anderson Imes
+1  A: 

You need to create a MEF ControllerFactory, which will use a MEF CompositionContainer to create a controller with its imports satisfied. Then you can just put an INewsService import on your controller.

Here is a sample which shows how you can do this.

EDIT: Here's another sample which looks a little bit simpler.

Daniel Plaisted
I dont like the way of adding a custom ControllerFactory, but it seems like the only good solution so far.
Marks