Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I export and import application services with say MEF?

I'm working with MEF right now, but the answer I'm looking for probably is irrelevant to MEF -- it's all dependency injection -- I'm just using MEF terminology as an example here.

Short background story, I read this article over at MSDN with focus on Composite Applications

In this figure there's three things, the shell, the application services and the modules. So that's a composite application.

alt text
(source: microsoft.com)

What I don't fully get is the application services part. What's the service, what does it look like? How do you expose a service through a module and how do you consume a service from a different module?

I'd really like to see some neat small code examples, nothing fancy but something to illustrate how all this comes to life (the application services part).

like image 550
John Leidegren Avatar asked Oct 26 '22 17:10

John Leidegren


1 Answers

Application Services, as far as MEF is concerned, are just another composable part. Any interface or class you can compose can act like a service.

Each service will have some interface or base class you want to implement. You can do these en masse via some type of IService interface (and use [ImportMany] to import them all), but often, you'll want different service types.

You'd then import this, as required, into your classes. For example, say you have a common interface library for services, and you provide:

public interface IDataRepostory
{
     public IList<MyType> MyTypes { get; }
}

You can then have a separate library export specific types:

[Export(typeof(IDataRepository))]
public class Repository: IDataRepostory
{
    // implement interface for this specific "service"
}

Your main program would then be able to import this as needed, and write code against it. For example, say you wanted to display customers, you'd need to load the customers from your data layer. If you wanted to load via your repository, you could import the repository into a specific portion of your application:

public class CustomersViewModel
{
     [Import]
     public IDataRepository
     {
         get; set;
     }

     // ...
}

You'd then get this service composed directly into your application.

This is considered an "Application Service" because it's an application specific implementation of some generic service - it's not a view related component, and it may be used throughout your application.

like image 58
Reed Copsey Avatar answered Nov 15 '22 05:11

Reed Copsey