Adding custom container to MEF
I have the following case using MEF .
开发者_如何学JAVAI build my solution by many modules, each module exists in a different dll . I use MEF as a choice to compose all my project. Its works fine , but sometimes I add for a module a service class say (AppService), this class simply has custom static methods which deal with generic service of this specific module . Now in this method I need some service which allready composed in MEF. The MEF container allready exists in the mail shell program . How can get reference to the reference I need . if I use [Import] it doesn't work. Example :
public class AppService
{
[Import]
public IService MyService {get;set;}
public static int Calc()
{
return MyService.Calc(); //My service is null
}
}
Thanks in advance ...
I think you actually have a few problems with that code.
1.Have you confirmed that your AppService
type is being composed? As you are not [Export]
-ing it, I can't see how that is generated. If you are not grabbing an instance of AppService
from the container, you have to manually satisfy the imports:
var service = new AppService();
container.ComposeParts(service);
2.Your class design has a static
method, where you are trying to access an instance
property. I'm assuming you're trying that for one of two reasons. Either, you assume the interface
for IService
supports static operations (which they can't), or you are calling an extension method that supports the IService
type, which is failing because the first argument of the suspected extension method is null:
public static int Calc(this IService service)
{
return service.Calc(); // failing perhaps?
}
If it is the latter extension method scenario, it would suggest something similar to 1) where you need to confirm that your AppService
type is being composed after it is instantiated.
The fact you have a static
method trying to access an instance
property would tell me that you probably need to rethink your design anyway, and remove the static
modifier:
public int Calc()
{
return MyService.Calc();
}
But again, your property is public, so is this method of any use at all? You current example shouldn't even compile, as you are trying to access an instance property from a static method.
精彩评论