Cedric Vandendriessche
Cedric Vandendriessche

Reputation: 728

Reference different model objects in .net class library depending on the project it's included in

My current solution has the following setup:

This setup has been working fine for me until I had to add data validation to the WPF project. I must use IDataErrorInfo on the model. I'm a bit stuck since IDataErrorInfo isn't supported in a portable class library.

What I tried was adding a new model class with the same name to my WPF project for every model class in my portable class library and inherit from the class in my library. I could then add all the validation code in the subclass. Problem is of course that my WPF project uses the class library with my repositories, which return instances of my model base classes (from the portable class library). Casting every single occurence of a model class in my WPF project doesn't seem the way to go..

So my question is: could I somehow let the repositories class lib return different model objects depending on the project it's used in? (always the base ones, but the subclasses when used in the WPF project). (I do realize it's not the best idea to let the repositories lib know about my wpf project, but if that's what it takes I'm fine with that.)

If there are other ways to achieve my goal, please tell!

Upvotes: 7

Views: 1202

Answers (3)

Wolfgang
Wolfgang

Reputation: 3490

This might be a good application for partial classes

In your class library the model classes are defined as partial:

public partial class MyModelClass
{
    ...
}

and the WPF application could add definitions e.g. like this:

public partial class MyModelCLass : IDataErrorInfo
{
    public string this[string columnName]
    ...
    public string Error { get; private set; }
    ...
}

Upvotes: 0

Daniel Plaisted
Daniel Plaisted

Reputation: 16744

It's complicated to set up, but you can probably define IDataErrorInfo in a portable library yourself, and then on platforms which include that type replace the PCL with the type with a library that has a type-forward for it.

See my answer here for a bit more on this: Is there any way I can implement IValidatableObject on Portable Class Library Project?

Upvotes: 0

LueTm
LueTm

Reputation: 2380

Sounds tricky. There are different solutions for that, that come to mind.

Make an interface for every model class you have.

  • Advantages: WPF app doesn't need to care about the concrete implementations. You can bring them in via repositories or something similar.
  • Disadvantages: Takes a lot of work, WPF designer doesn't work well with interfaces, so you'd have to create fakes or:

Generate your classes/interfaces with T4

  • Advantages: You don't have the maintenance that the interfaces can bring. Also you don't have to reflect changes many times (Model, Interface, Fake).
  • Disadvantages: You'll have to dig into it :), other's don't come to mind at the moment.

Upvotes: 1

Related Questions