Use different versions of the same class in host/plugin scenario - wpf

I have developed a WPF plugin-based application whereby plugin assemblies are dynamically loaded into a "host" application and both the host application and its plugins reference common assemblies.
If at some point in the future I wish to tweak a class of the common assembly, I don't want to have to recompile all of the plugins in order for them to work within a host application which might be running with a different version of common assemblies.
Scenario:
There are 2 versions of the common assemblies (1.1.0.0 and 1.2.0.0), signed and deployed the Global Assembly Cache. Each contains a class "Foo" which remains untouched between versions. Due to the architecture, Foo has to stay within the common assembly.
The host application is built against common version 1.1.0.0 and provides a base class from which view models within all plugins can derive; its function is very UI centric, so it has to stay within the host application.
Plugin #1 is built against common version 1.1.0.0
Plugin #2 is built against common version 1.2.0.0
Relevant third party components used: Microsoft's Prism and ServiceLocation and Castle (Windsor)
Common:
public class Foo
{
// Some useful properties
}
Host:
public class ViewModelBase<T> where T : Foo
{
// Some useful behaviour
}
Plugin #1:
public class ViewModel : ViewModelBase<Foo>
{
}
Plugin #2:
public class ViewModel : ViewModelBase<Foo>
{
}
ISSUE:
Upon loading Plugin #2, I receive a ReflectionTypeLoadException due to the fact that the Foo class of version 1.1.0.0 is not considered the same as the Foo class of version 1.2.0.0 and so using Foo as the type parameter for the view model in Plugin #2 is invalid.
IDEAS:
Using a more immutable "core" common assembly to contain the Foo class (but in the end, this would entail taking too many classes from too many different assemblies) and so isn't an option
Using assembly redirects (but forcing plugins to use the same version of common assemblies as the host application does not guarantee that a plugin that works during development will continue to work post-deployment, unless rules are put in place that ensure no breaking changes can be introduced using obsolescence attributes)
Has anyone managed to get a truly side-by-side (not to be confused with .NET framework side-by-side) scenario like this working (be it in single or multiple app domains)?
Thanks very much,
Rob

We ended getting around the issue using assembly redirects in the app.config file of the Host application.

Related

Prism 4 WPF App - Solution Architecture with MVVM, Repositories and Unit of Work patterns implemented

I'm new to .Net and trying to learn things. I'm trying to develop a Prism4 WPF app with
Visual Studio CSharp 2010 Express Edition,
Prism v4,
Unity as IoC,
SQL Server CE as data store.
I've studied a lot(?) and infuenced by this and this among others, and decided to implement MVVM, Repository and UnitofWork patterns. This application will be a Desktop application with a single user (me:-)
So, I've created a solution with the following projects:
Shell (Application Layout and startup logic)
Common (Application Infrastructure and Workflow Logic)
BusinessModuleA (Views and ViewModels)
BusinessModuleA.Model (Business Entities - POCO)
BusinessModuleA.Data (Repositories, Data Access (EF?) )
BusinessModuleB (Views and ViewModels)
BusinessModuleB.Model (Business Entities - POCO)
BusinessModuleB.Data (Repositories, Data Access (EF?) )
My questions are:
Which projects should reference which projects ?
If I implement Repositories in 'BusinessModuleX.Data', which is
obvious, where should I define IRepositories ?
Where should I define IUnitOfWork and where should I implement UnitOfWork ?
Is it ok if I consume UnitOfWork and Repositories in my ViewModels ?
Instict says it is bad design.
If (4) above is bad, then ViewModel should get data via a Service
Layer (another project ?). Then, how can we track changes to the
entities so as to call the relevant CRUD methods on those objects at the Service Layer?
Is any of this making any sense or am I missing the big picture ?
Ok, may be I've not made myself clear on what I wanted exactly in my first post. There are not many answers coming up. I'm still looking for answers because while what #Rachel suggested may be effective for the immediate requirements, I want to be careful not to paint myself into a corner. I've an Access Db that I developed for my personal use at Office, and which became kind of a success and now being used by 50+ users and growing. Maintaining and modifying the access code base has been fairly simple at the beginning, but as the app evolved, began to fall apart. That's why I have chosen to re-write everything in .Net/Wpf/Prism and want to make sure that I get the basic design right.
Please discuss.
Meanwhile, I came up with this...
First off, I would simplify your project list a bit to just Shell, Common, ModuleA, and ModuleB. Inside each Project I'd have sub-folders to specify where everything is. For example, ModuleA might be separated into folders for Views, ViewModels, and Models
I would put all interfaces and global shared objects such as IUnitOfWork in your Common project, since it will be used by all modules.
How you implement IUnitOfWork and your Repositories probably depends on what your Modules are.
If your entire application links to one database, or shares database objects, then I would probably create two more projects for the DataAccessLayer. One would contain public interfaces/classes that can be used by your modules, and the other would contain the actual implementation of the Data Access Layer, such as Entity Framework.
If each Module has it's own database, or its own set of objects in the database (ie. Customer objects don't exist unless you have the Customer Module installed), then I would implement IUnitOfWork in the modules and have them handle their own data access. I would probably still have some generic interfaces in the Common library for the modules to build from though.
Ideally, all your modules and your Shell can access the Common library. Modules should not access each other unless they build on them. For example, a Customer Statistics module that builds on the base Customer module should access the Customer module.
As for if your ViewModels should consume a UnitOfWork orRepository, I would have them use a Repository only. Ideally your Repository should be like a black box - ViewModels can Get/Save data using the Repository, but should have no idea how it's implemented. Repositories can get the data from a service, entity framework, direct data access, or wherever, and the ViewModel won't care.
I'm no expert on design architecture, however that's how I'd build it :)
I would highly recommend you to get the Introduction to PRISM and Repository pattern inside Design Patterns Library training videos. They are great ones. Hope it helps

Generating Silverlight service reference - how to tell what is causing proxy classes to be generated

I have a large object structure that I'm wanting to share between a .Net4 backend and a Silverlight 5 front end. I've created two class library projects of the appropriate type, and have my object structure implemented in the .Net library, and linked into the SL library. On the Silverlight client side I am referencing the Silverlight class library. When I generate the service reference I have checked the option to "Reuse types in referenced assemblies". However when I generate the service reference I am finding that types that are in referenced assemblies are still being generated. It is only certain types, and appears to be largely collection types (attributed with <CollectionDataContract>).
I have a main object that has many properties which are generally either List<MyTypeA> or in some cases they are MyListTypeB, where MyListTypeB inherits from List<MyTypeB>. It seems to be the classes similar to MyListTypeB that are causing the proxies to be generated. These are all attributed with <CollectionDataContract> and have a default constructor.
I also find that even though the project where I am adding the service reference to has a reference to the other SL project containing the entities, when I update the service a new reference directly to the dll is also being added to the project. I'm not sure why this is happening, or if it is causing confusion in the service proxy generation
Is there any way to tell what classes/properties are causing the service generation to generate proxy classes? Or is it a case of trial and error having to comment out attributes until they aren't generated and hone in on the problem class?
I have now found out about the use of the svcmap file, and updating the CollecitonMappings elements to include my collection types, described here:
http://mostlydevelopers.com/blog/post/2009/12/14/Configure-WCF-Service-ndash3b-Reuse-Collection-Types-Issue.aspx
It seems a little unusual that the svcmap functionality is so undocumented.
I was able to add an entry int he svcmap file similar to the following:
<CollectionMappings>
<CollectionMapping TypeName="MyNamespace.MyType" Category="List" />
</CollectionMappings>
And then when I updated the service reference the proxy collections are not generated.

What is the correct way to solve the ambiguous reference issue in WCF services?

Project Structure
I have a silverlight project SLProj, that references a silverlight class library project called ServiceClients. ServiceClients has two wcf service references, Svc1.svc and Svc2.svc. Both Svc1.svc and Svc2.svc are in two different WCF projects which use the same set of DataContracts which are again in a different class library project called MyDataContracts.dll.
Problem description
Now in my ServiceClients project I get an ambiguous reference issue when I need to use a datacontract class which is present in both the service references. If this were a winforms or webforms project, I could reference the MyDataContracts.dll and reuse the common types. But since, this MyDataContracts.dll was built using a non silverlight class library, it can't be referenced in the silverlight project
Workaround...
I am not sure if this below is the best method to go about taking care of this issue. Can anybody let me know if there is a cleaner way to solve this problem, or is this the best way we have so far?
create a single service reference.
click the 'show all files' button in the solution explorer
drill into the service reference and find Reference.svcmap and open it
find the MetadataSources section
add a second line to include the address to your second service. for example:
MetadataSource Address="http://address1.svc" Protocol="http" SourceId="1"
MetadataSource Address="http://address2.svc" Protocol="http" SourceId="2"
save, close, and update service reference.
Use Automapper
Map the DataContracts with AutoMapper.
You will have to invest some time in understanding AutoMapper and reworking your application. Also AutoMapper adds overhead because all data objects will be mapped. But first you will have a clean solution without hacks and second you gain a decoupled and simple data object layer just for your client. Once done you can forget the mapping but you stay flexible for future changes.
If you never have worked with Automapper it's important to play around with it before starting. Automapper is special and needs some time to familiarise with it.
So there. These are the rough steps:
1. Create a subdirectory and sub-namespace Data and copy the DataContracts. Remove the attributes and properties your client doesn't need because these mapped classes live only in your client. You can also change some types or flatten some complex properties.
2. Create an AutoMapperInit.cs like described at Automapper (read the Getting Started Guide). Use the conflicting references like this:
using ref1 = YourProjectServiceReference1;
using ref2 = YourProjectServiceReference2;
3. Wrap the service client like this:
Example GetExample() {
return AutoMapper.Map<ref1.Example, Example>(ref1.YourService.GetExample());
}
The wrapper also needs the same using directives as in step 2.
4. In this wrapper add a static initializer like this (assuming your wrapper class is called Wrapper):
static Wrapper() {
AutoMapperInit.CreateMaps();
}
5. Omit service references in the client and use using YourClient.Data;, the namespace you created in step 1.
Your client is now decoupled from the service and you don't have conflicts anymore.
Disclaimer: I am not affiliated with AutoMapper. I just used it in a project with a similar problem and am happy with it and wanted to share my experience.
Your workaround is actually quite OK. We've used it in several projects like this with 3 service references. It is actually a workaround for the IDE which for some reason only allows to select one service to create a service reference at a time.
Another thing you could try-out is to multi-target your shared contract to .NET and Silverlight, using the same codebase. Details on how to do such thing is described in http://10rem.net/blog/2009/07/13/sharing-entities-between-wcf-and-silverlight. Might be more work but feel less hacky.

WCF from Silverlight without using Add Service Reference

David Betz describes in his article how to create reference to WCF without using "Add Service Reference" option:
http://www.netfxharmonics.com/2008/11/Understanding-WCF-Services-in-Silverlight-2
Once WCF service is created, these are the statements within the silverlight:
BasicHttpBinding basicHttpBinding = new BasicHttpBinding();
EndpointAddress endpointAddress = new EndpointAddress("http://localhost:1003/Person.svc");
IPersonService personService = new ChannelFactory<IPersonService>(basicHttpBinding, endpointAddress).CreateChannel();
...
How does one references the types (such as IPersonService interface) created in WCF from Silverlight when I do not use "Add Service Reference" to buid proxies?
Idea is to reference assemblies that contain WCF data contracts in silverlight application, and to do that you need to fool VS so it thinks assembly is a SL assembly, he describes this in detail here
http://www.netfxharmonics.com/2008/12/Reusing-NET-Assemblies-in-Silverlight
and its not so easy, here is what needs to be done
Just use the same ILDasm/Edit/ILAsm
procedure already mentioned to tell
the assembly to use the appropriate
Silverlight assemblies instead of the
.NET assemblies. This is an extremely
simple procedure consisting of nothing
more than a replace, a procedure that
could easily be automated with very
minimal effort. It shouldn't take you
much time at all to write a simple
.NET application to do this for you.
It would just be a simple .NET to
Silverlight converter and validator
(to test for assemblies not supported
in Silverlight). Put that application
in your Post Build Events (one of the
top 5 greatest features of Visual
Studio!) and you're done. No special
binary hex value searching necessary.
All you're doing is changing two well
documented settings (the public key
token and version).
Second solution is a file level solution , you use add link option on files that contain your required data contracts implementations to SL and make sure they only contain types that allow to build SL and dont reference a lot of external assemblies , usually those conditions should be met for WCF services & data contracts.
I can write more but it would be just the copy paste from that link
You also have to split all methods declaration in you IPersonService according to Async pattern (BeginXXX/EndXXX) since Silverlight supports only asyncronous WCF (even in background threads).
As a help to do this, you may add Service Reference, then copy generated IPersonService (all methods will be decoupled) from Reference.cs. Then you may remove the reference.
However, if your service contract is often changed, you have to repeat Add-Service procedure again, and starting from this, I would say, it's easier just use Add-Service-Reference feature, rather than sharing the contract with your app server.
Only one thing that I would like detect. Often you need in namespaces with more complex support of NET within your WCF service. Therefore you must have real reasons to reference to Silverlight subset within your WCF service (or service library). There are many ways to
use so named traditional ways by Add Service Reference. They are presented in good article enter link description here.

How to avoid coupling when using regions in Composite WPF

I have an application designed using Microsoft's Composite Application Library. My shell has several regions defined so that I can inject content from separate modules. I'm looking for a design pattern that will reduce the coupling that these regions introduce.
In all examples I have seen, regions are defined and accessed using a string in a static class in the infrastructure project.:
<ItemsControl cal:RegionManager.RegionName="{x:Static inf:RegionNames.TabRegion}">
public static class RegionNames
{
public const string TabRegion = "TabRegion";
}
This introduces an dependency on the shell from the infrastructure project, because part of the infrastructure project must now match the shell. The CAL RegionManager throws an exception if you attempt to access a region which is not defined, so I must ensure that the infrastructure and shell projects are kept in sync.
Is there a way to isolate the shell's regions so that they are defined only within the shell (no region names in the infrastructure project)?
Is there a way to make regions optional, so that shells can be swapped out even if they don't have all the same regions? (An example: One shell has menu and toolbar regions, another only has the menu... modules should be able to inject into the toolbar if it's available, without failing when it's not)
Update - More details on my architecture
In response to depictureboy's answer below, I wanted to describe the way my system is set up... perhaps there will be more good feedback on it.
I am treating the Infrastructure and Shell projects as generic libraries, and I have several applications which use them. The Infrastructure project provides "framework" code and resources (like MVVM stuff, reflection, icons), and my Shell is a generic host window, with the basic window layout (menus, toolbars, status bar, main content area). The applications all share a common look and behave similarly because they share the shell.
My applications get their individual functionality from the modules which get loaded, so I have a bootstrapper project per application which pulls everything together (infra, shell, modules).
I imagine if I ever need to develop a brand new application that is very different from the current ones, I will be able to re-use the infrastructure project, but not the shell. That is why I am curious about decoupling the infrastructure project and the shell.
I think you have your logic backwards. Your shell is the glue that binds everything together. In my mind you want the infrastructure and shell tightly coupled because they are the application. Your modules are the parts of the application that will be changing and switching around dynamically. You want your shell regions to be static so that, for example, another developer could write a module for your application knowing where his different views were going to be placed and how the application should behave with his module attached. The Infrastructure project is there to be the go between between your shell and its modules...thats just a fact of life at least in my book. One of the WPF gurus may come up with something that absolutely blows that out of the water tomorrow....

Resources