1

Let say I have this piece of code

public interface IFoo
{
}

public abstract class FooBase<TModel> : IFoo
{
    public T Create<T>() where T : TModel;
}

public class Foo : FooBase<ModelBase>
{
    public TModel Create<TModel>()
    {
        return Activator.CreateInstance(typeof(TModel));
    }
}

public abstract class ModelBase
{
}

public class ModelFoo : ModelBase
{
}

public class ModelBar : ModelBase
{
}

Now, let say I have this class

public static FooProvider
{
    public IFoo Get<TModel>()
    {
        var provider = ...; // find which IFoo class has generic TModel
        return provider;
    }
}

And I can manage to call this with

IFoo provider = FooProvider.Get<ModelBar>();  // -> instance of Foo

But I get an instance of IFoo, therefore don't have access to the FooBase methods. Is it possible to implement IFoo (or an intermediary abstract class) to provide a method declaration that can be called without (necessarily) casting the return value provider?

Ideally, I'd like to be able to do

ModelBar bar = FooProvider.Get<ModelBar>().Create<ModelBar>();

Is it possible?

2
  • 2
    What about returning FooBase<TModel> instead of IFoo?
    – Jon
    May 9, 2013 at 8:42
  • Because I need to return FooBase<ModelBase> when calling Get<ModelBar>. As you can see, TModel is ModelBar, not ModelBase and I cannot cast Foo into FooBase<ModelBar> May 9, 2013 at 8:51

2 Answers 2

2

As the question evolved, I'm posting second answer. Here's a sample class hierarchy which:

  • allows to use same provider for many model types
  • allows to construct many different providers and models in a consistent way
  • checks provider/model compatibility at compile time
  • does not need casting during usage

Code:

public interface IWhatever { }

public class Foo { }
public class Foo2 : Foo, IWhatever { }

public class Bar { }
public class Bar2 : Bar { }
public class Bar3 : Bar, IWhatever { }


public interface IModelProvider<T>
{
    U Create<U>() where U : T;
}

public class FooProvider : IModelProvider<Foo>
{
    public U Create<U>() where U : Foo
    {
        // create a proper "U" - for example Foo or Foo2
        return Activator.CreateInstance<U>(); // simpliest
    }
}

public class BarProvider : IModelProvider<Bar>
{
    public U Create<U>() where U : Bar
    {
        // create a proper "U" - for example Bar, Bar2 or Bar3
        // more verbose
        if (typeof(U) == typeof(Bar)) return (U)new Bar();
        if (typeof(U) == typeof(Bar2)) return (U)(object)new Bar2();
        if (typeof(U) == typeof(Bar3)) return (U)(object)new Bar3();

        throw new Exception();
    }
}

public class WhateverProvider : IModelProvider<IWhatever>
{
    public U Create<U>() where U : IWhatever, new()
    {
        // create a proper "U" - for example Foo2 or Bar3
        return new U(); // really the simpliest
    }
}

    public class VeryGenericProvider : IModelProvider     {         public TModel Create() where TModel : new()         {             return new TModel();         }     }

public class ProviderFactory
{
    public static IModelProvider<T> Get<T>() where T : new()
    {
        // somehow choose a provider for T, dumb implementation just for example purposes
        if (typeof(T) == typeof(Foo)) return (IModelProvider<T>)new FooProvider();
        if (typeof(T) == typeof(Bar)) return (IModelProvider<T>)new BarProvider();
        if (typeof(T) == typeof(IWhatever)) return (IModelProvider<T>)new WhateverProvider();

        return VeryGenericProvider<T>();
    }
}

public static class ProviderTest
{
    public static void test()
    {
        Foo foo = ProviderFactory.Get<Foo>().Create<Foo>();
        Foo2 foo2 = ProviderFactory.Get<Foo>().Create<Foo2>();

        // Bar2 bar2 = ProviderFactory.Get<Foo>().Create<Bar2>(); - compile error
        Bar2 bar2 = ProviderFactory.Get<Bar>().Create<Bar2>(); // - ok!

        Bar3 bar3 = ProviderFactory.Get<IWhatever>().Create<Bar3>();
    }
}

This code compiles, but I have not run it. Note that the final usage in the "test" does perform type checks and does not need any casts -- but the provider's internal implementation surely will need to cast a few things - for example please see the BarProvider which manually constructs the objects. Even if "we know" for sure that U is Bar2, there is no way to tell the language to upgrade the constraint over U from Bar to Bar2 - hence a double cast is needed.

I mean this:

return (U)new Bar(); // is ok because U is constrained to 'Bar'

versus

return (U)new Bar2();         // will not compile, U:Bar is not related to Bar2:Bar
return (U)(object)new Bar2(); // is ok: temporary cast to object 'erases' type information
11
  • 1
    You can have a slightly stronger compile time check in your code to determine whether creating a new instance will succeed using the new() generic constraint: U Create<U>() where U : T, new() which will enable you to simply return new U(); rather than return Activator.CreateInstance<U>(). May 9, 2013 at 9:29
  • Yes indeed! I copied the object-creation code from the question, I assume it will be replaced with something more complicated, as Activator can accept construciton parameters and the new() constraint cannot (at least as of .Net4/.5). I didn't want to complicate the sample more than absolutely needed. May 9, 2013 at 9:36
  • In fact, as I already wrote 3 different sample providers, I've upgraded WhateverProvider to use the new() constraint. Thanks for suggestion! May 9, 2013 at 9:37
  • So, this looks quite like my original implementation. All that tells me is that I cannot call ProviderFactory.Get<Foo2>(), which is what I was trying to do. Thansk you for your time! May 9, 2013 at 9:45
  • You can do that. ProviderFactory.Get<Foo2>().Create<Foo2>() will compile - the only thing you must correct in the above example is to make the GET implementation recognize the Foo2 and return a proper provider for it (here, a FooProvider or WhateverProvider as both of them can construct Foo2. First on behalf of Foo inheritance, second on behalf of IWhatever implementation) May 9, 2013 at 9:48
1

Did you mean

ModelBar bar = FooProvider.Get<ModelBar>().Create<ModelBar>();

or rather

ModelBar bar = FooProvider.Get<ModelBar>().Create();

?

I find the former a bit strange unless you have some cases where first ModelBar is actually ModelBarBase or IModelBar and the latter ModelBar is in fact the final constructable type.

Anyways, I also find your class layout a little strange, as in your code example the Get() and Create() come from the same class (Foo/FooBase). I think you messed up with SRP here.

I'd recommend:

public class FooProvider
{
    public static Provider<T> Get<T> { return new Provider<T>(); };
}

public class Provider<T>
{
    public T CreateDirect()
    {
        return Activator.Create<T>();
    }

    public TDerived CreateDerived<TDerived>() where TDerived : T
    {
        return Activator.Create<TDerived>();
    }
}

and in this setup you can:

class IMyInterf {}
class MyType : IMyInterf {}
class MyChildType : MyType {}

MyType tmp1 = FooProvider.Get<MyType>().CreateDirect();

MyChildType tmp1 = FooProvider.Get<MyType>().CreateDerived<MyChildType>();

MyChildType tmp1 = FooProvider.Get<IMyInterf>().CreateDerived<MyChildType>();

This is only sketch, written by hand without compiling, but it shows the general idea.

If you remove "CreateDirect" and rename "CreateDerived" to just Create, you'd get something similar to your code, but simplier. And of course, you may now mix and squash those two separate classes into one if you really need, but I see no real point in it :)

EDIT:

And of course instead of Provider<T> you can introduce a ProviderBase<T> and multiple OrangeProvider:ProviderBase<Orange> just for the sake of easier building/finding the proper provider, but still the actual Get<> will have to return the actual ProviderBase<T> or IProvider<T>.

5
  • The idea behind my design is that I want to return the provider for a given model, and I'd like to be able to substitute this provider when testing (with a Mock provider). Your suggestion does not allow this. Plus, one provider can serve different (known) related model types. May 9, 2013 at 9:02
  • I already told you this is a sketch/overview. The last two lines show that one provider typef by "X" can construct "Y" or "Z", so the one-for-many-types is fulfilled. Mocking/substituting the providers for testing is trivial: instead of returning Provider<T> from the Get<T> - return IProvider<T> - and now your static FooProvider can return a mock while in test environment.. May 9, 2013 at 9:05
  • I mean, even with support for mocking, there's still no need to mix the factory/provider/model classes. May 9, 2013 at 9:07
  • I'm from a Java background, and what I'm trying to do is fairly easy as the generics don't behave the same. So, what you're saying is thst I need to have a provider for every model types? May 9, 2013 at 9:07
  • I've just posted second example. Please give it a look. May 9, 2013 at 9:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.