Creating a Silverlight library with dependecies composed via MEF - c#

I have a Silverlight 4 library L which has a dependency that is to be provided at run-time via a plugin P.
I am using a DeploymentCatalog along the lines of the example provided by MEF documentation and all is well: the XAP of the plugin P is correctly downloaded asynchronously and the import is satisfied.
However, I cannot control the details on the Silverlight application A that will be using library L and I cannot exclude that A itself might want to use MEF: therefore it's possible that at some point A might issue a CompositionHost.SatisfyImports(...) CompositionHost.Initialize(catalog) call for its own purposes which I understand can only be invoked once.
Am I missing something here or partitioning the application across multiple XAPs can only be achieved if one has complete control of the Silverlight application and libraries?
Stefano

CompositionHost.SatisfyImports can be called many times. CompositionHost.Initialize can only be called once. As a library, it is not a good idea to call that method because the application may do so. Since you need to create and use a DeploymentCatalog, it's probably better if you don't use CompositionHost at all in your library, since you want to avoid calling the Initialize method, which would be the way to hook the CompositionHost to the DeploymentCatalog.
You can create your own CompositionContainer hooked up to the DeploymentCatalog and call GetExports or SatisfyImports on the container you created. CompositionHost is pretty much just a wrapper around a static CompositionContainer.

It's not usually a good idea to tie yourself to a single dependency injection container in a library, instead you'd usually want to abstract that away using something like the CommonServiceLocator, which leaves the choice of IoC container a preference of whoever is consuming your library.

I only started with MEF in Silverlight a month ago, so I'm definitely not an authority.
The first thing I noticed is that CompositionHost.SatisfyImports has been replaced with CompositionInitializer.SatisfyImports .
Second I could not find any reference to "SatisfyImports can only be invoked once"
My scenario is the following:
I have a BL xap which I use/link to from my application
The BL has some Imports that will be satisfied by calling SatisfyImports from the Application
The BL also has some imports that
cannot/will not be resolved until a
certain custom (third party)
module/xap will be loaded (loaded
when demand that is). When the custom
module becomes available (is loaded)
I solve the missing imports with an
extra call to
CompositionInitializer.SatisfyImports:
E.g:
If DomainSpecificModuleLogic Is Nothing Then
'this is required to trigger recomposition and resolve imports to the ThirdPartyModule
System.ComponentModel.Composition.CompositionInitializer.SatisfyImports(Me)
End If
So I have multiple calls to SatisfyImports (at different moments in time) and no problems due to this -> you do not required control over the whole application, just make sure that when someone accesses an object from your library that uses MEF, you have a call to SatisfyImports
Note: my BL is a singleton, so for sure I am calling SatisfyImports on the same object multiple times.

Related

Using IoC in an application that use a library that doesn't use IoC

I am currently using a library (SuperWebSocket) which is a websocket server library that use a bootstrap which know which instances to load from a configuration file. I have implemented a bootstrap class for this (however the instances arent loaded using IoC). Also the commands from this server are loaded from assemblies reflection. I wanted to use this server in conjonction with my DAL and service layer which use IoC. My main problem is that i can't find a way to put this Console Application (Server) and cooperation with the lib in an IoC scenario without having to end up using the ServiceLocator.
Normally the kernel (Ninject) should be located at the composition root (Look like to be the best practice from many around..) which is rather not possible to do in this case or at least i didn't found how so that why i am here. Also the commands are loaded from assemblies reflection. I could implement a CommandLoader however this is still a problem cause they all inherit from the same interface (Multibinding maybe?). I could make custom interface for each of them but i still can't find a way to load them automatically. Even if i found a way to load them, i still have to be able to get service from attributes which is not easy to do.
Any suggestions ?
If I understand your question correctly then the library is the entry point for all work done. In this situation it depends on the framework what to do. Here are some things you can do the first things are the preferred ones:
Inspect the library and find some way to hook into the framework to intercept the creation of your objects.
Call kernel.Inject(this) after an object is created by the library. Have a look at the Ninject.Web extension. There we added some base classes e.g. NinjectWebPage for WebPage. This new base class calls kernel.Inject after creation. New web pages can now be derived from that base class and use property injection to get dependencies.
Use the ServiceLocator pattern in the objects created by the libray. But just at this level. Anything deeper should use dependency injection.

MEF Best practices: Where in the application I create container and where to call Compose()?

I have decided to use MEF for a plugin pattern I have and found MEF easy to pick up and not intrusive at all. I looked at samples and found them very easy to work with.
However, as soon as started implementing, I started struggling with the composition. Let's say I have a Class which has [ImportMany] on one of its properties. All examples I have seen, they create the Container in the class which has imports (let's call it composable) and basically the class composes itself. That might be OK for an example but surely putting knowledge of how the plugin gets populated is too much for the composable to know.
I can happily create a singleton container and access it in my composable but again the composable has to explicitly call Compose() on itself and I am not happy with that either as it is like a dependency injection scenario where the class pro-actively calls the Resolve() on the container. So I do not want to use it for just Service Location.
To make the matters worse I am also using Windsor Castle for DI and I am not sure how MEF and Windsor must work together.
I have really looked around and have not been able to find any guidance and sample on how to do MEF right. Now it might be that I have not looked around or I do not know MEF well enough (which is true) but will value your views from the experience of actually using it in the real world.
Do not do that. I used MEF for my last project and I wish to not do that.
There's a good idea behind it (composition) and I was do that manually for years. I was happy for the first official version in .NET 4.0 but there a re still a lot of design problems.
Unfortunately it's part of Microsoft policy to leave testing and bug finding to end users and feedback the hard-earned bugs and suggestions.
MEF is good if you use the way the example says. As soon as you need a little change you will find there's not enough documentation and nobody will answer you. Here are some of my never resolved issues with MEF and you can find my questions in codeplex.com which never had been answered by the developer team:
1) How to pass parameters to part's constructors (they may say use ExportFactory which is shipped in codeplex version but I wasted a long time on this, and I can say there's not an acceptable solution for that)
2) How to set configurations for parts ? (I ended-up passing configurations to parts through a method which is a bad idea, but the best available)
3) MEF is very slow because it use reflection under the hood. For my case loading 1,000 parts takes 60 seconds.
4) Debugging is awesome. You get unclear messages. You will end-up downloading the full source from codeplex and search your exceptions inside the code.
After all I think if you have other choices, let MEF gets mature and use the next version.
I just shared my own experience.
The recommended pattern is for you to create the container once in your hosting code, and only access it from there to get the "root" part. You would call container.GetExport<Root>() if it's OK for MEF to create the part for you, otherwise you would call container.SatisfyImports(root).
The root part should import the things it needs, and the parts supplying those exports should import what they need, and so on. MEF will create the whole graph and none of the parts need to call into the container directly. The samples often have very few different parts, so it isn't always obvious that the container creation and composition should only occur once, even in more complex applications.
There are situations where you may have object that need their imports satisfied, but can't be created by MEF. An example of this is WPF/Silverlight UI objects that are created by the Xaml parser. In this case you might resort to a service which allows these objects to request that their imports be satisfied.
I don't have much advice for how to use MEF and another DI container in the same application. If there isn't much interaction between the parts of the system composed with MEF and Windsor it might work without much trouble. If you need components from one container to be injected with components from the other container, it won't be as simple. One way would be to have a service that a component would have to call to resolve its dependencies from the other container. The other possibility would be to have the containers themselves linked. You can do this in theory with MEF by writing an ExportProvider that accesses the Windsor container. In practice it would require a very deep level of knowledge about MEF, and it might not be possible to get it to work exactly how you'd like.

Component oriented design: Problems with dependencies in dialogs

I have a modular application, it behaves quite like a plugin system. Module B is dependent on Module A. When B is present, then some dialogs (titles etc.) need to be altered in Module A. Also, a different entity should be used for a list when Module B is present, which I want to include in Module B, so A doesn't know about it during compile time. Creating an abstract base in A for the entity is something I want to avoid as well.
How would you implement this requirement? The modules can communicate in various ways:
1.) Microsoft Unity is used for Object creation and dependency injection
2.) The modules can communicate via a Message-System.
3.) There's an EventAggregator which all the modules can use
I don't want to sublcass the dialog in Module B and just alter the typemapping in unity, because then I'd have to provide the whole dialog in another module. Also, if some other module wants to make other changes to the dialog, it'd be impossible.
Suggestions welcome!
Without knowing specific details, I would use interfaces to blend the plug-in components/modules. Require that each plug-in component implement an interface -- say IPluginComponent or whatever makes sense. (Actually, only components that must communicate or interact would actually be required to implement the interface.) Once all modules are loaded, the host application can fire methods or events on the components.
Personally, I like to keep things data-driven and simple as much as possible; so I might favor a "two-phase" pass through the modules. This keeps the dependencies between modules simple. So in the first phase, when all components are loaded, the host application fires the "ContributeSharedData(Context ctx)" method, where each component sets any values in a shared context. (This might also be called "Init(ctx)".) The context might be as simple as a name-value-pair collection, e.g. Module B says *coll["ModuleB_Installed"] = true*, or it could add itself to a list of modules, or... the possibilities are endless. The context can be whatever class or structure is required to enable these components to work together.
The next pass -- if required -- would be for the components/modules to configure themselves based on the shared context. So the host might run through all the modules supporting the shared interface and fire the "Configure" method or event. Then ModuleA for instance can look in the context and see that ModuleB is installed, and configure its interface accordingly.
If an interface doesn't make sense for your situation, you can use any method of contributing shared data in a generic way to a common location, e.g. messaging or other common classes.
Hope this helps!

.NET 3.5: Dynamically adding classes without recompiling

I'd like to build an infrastructure that will monitor a server and check ping, response time, and more.
The catch is that future checks (for example: does a certain file exist) will be added without recompiling the infrastructure.
How do I build it in such a way that will enable me to attach inherited classes with different functionality, and execute them without recompiling?
Thanks!
In addition to creating an interface and defining a single entry point for your new library, you could create an attribute which identifies the classes that you need to load or the methods that you need to call. You then use reflection to look at all the DLLs in a certain path, and instantiate / run whatever contains your attribute.
I've built a similar application that had to perform a number of health checks on a system, and needed to be extensible. The application started, looked through all the DLLs in a specified path and for each class with the 'TestAttribute' decoration it would create an instance and run the 'Execute' method.
The use of an attribute means that you don't need to specify which DLLs to process (doesn't need to be in config / database) because it's safe to process every DLL, and only those decorated with the attribute will do anything.
Implement an interface, and the provider pattern, then you can plug anything in that you like. MSBuild is a great example of this, with a simple interface you can add any type of task you like to your build process - follow the same sort of pattern.
Sounds like you could use some kind of 'plugin' mechanism. Define a basic interface and you can compile every "check/action" into a separate assembly. Load all your assemblies dynamically from file and call execute the check/action via the defined interface.
The interface could be just as simple as this, for starters:
public interface IMonitorAction
{
bool Exectute();
}
This infrastructure allows you to add more checks by just creating another assembly file implementing the interface next to the existing ones.
Of the top of my head.
I presume you can re-start you application.
Have a file that lists all the DLL's to load that implement your required functionality. Each DLL should have the same name entry point. Load each DLL, call the method, unload DLL. loop.
Caveat: I've never done anything like this, so I may be talking hot air.
Adding to #slugsters answer, instead of building your own extensibility infrastructure, take a look at extensibility libraries like MEF.

Is MEF an all-or-nothing affair?

I've had a few questions about MEF recently, but here's the big one -- is it really all-or-nothing, as it appears to be?
My basic application structure is simply an app, several shared libraries that are intended to be singletons, and several different plugins (which may implement different interfaces). The app loads the plugins, and both the app and all plugins need to access the shared libraries.
My first go at MEF was fairly successful, although I made some stupid mistakes along the way because I was trying so many different things, I just got confused at times. But in the end, last night I got my smallish test app running with MEF, some shared libraries, and one plugin.
Now I'm moving onto the target app, which I already described. And it's the multiple plugins part that has be a bit worried.
My existing application already supports multiple plugins with different interfaces by using Reflection. I need to be able to uniquely identify each plugin so that the user can select one and get the expected behavior exposed by that plugin. The problem is that I don't know how to do this yet... but that's the topic of a different question.
Ideally, I'd be able to take my existing plugin loader and use it as-is, while relying on MEF to do the shared library resolution. The problem is, I can't seem to get MEF to load them (i.e. I get a CompositionException when calling ComposeParts()) unless I also use MEF to load the plugin. And if I do this, well... then I need to know how to keep track of them as they get loaded so the user can select one from a list of plugins.
What have your experiences been with trying to mix and match these approaches?
MEF is designed to let you easily load plugin assemblies. If you have control over the plugins (by which I mean that you can add MEF export attributes) then there is no need to keep your own plugin loader which uses reflection. MEF does all that for you.
That being said, "mixing and matching" MEF with other technologies is certainly possible. It sounds like your problem is that if you use your own plugin loader, you don't add those plug-ins to the MEF container. As a result, you get a CompositionException for parts which try to import the selected plug-in.
To add a plugin that you loaded with your own code to the MEF container, you can use the ComposeExportedValue like this:
container.ComposeExportedValue<IPlugin>(selectedPlugin);
edit: I see what you mean now by "all or nothing". Your problem is that in order to be able to import parts with MEF, you also need to construct the object with MEF. This problem then cascades to the object which normally created that object, etc. all the way to the application root.
To avoid this "all or nothing" effect, you can compromise by exposing the MEF container as a global variable (i.e. static field). That way, classes can access the MEF container and pull exports from it, e.g. by calling Program.Container.GetExportedValue<MyDependency>() in the constructor.
edit2: If you have an object that was not constructed by MEF, then there are two ways to add it to the container.
The first is to call container.ComposeExportedValue<IMyContractType>(myObject);.
The second is to return the object in a property getter, and then mark the property itself with an [Export(typeof(SomeType))] attribute.

Categories