I have the following conceptual model:
public interface IFoo<out T> { T Data { get; } } public struct Foo<T> : IFoo<T> { public Foo(T data) : this() { Data = data; } public T Data { get; private set; } } public class FooService<T> { ... public Foo<T> Get(string id) { ... } }
Then I try to use it in a way that is conceptually equivalent to this:
// Create and register a few FooService instances ServiceLocator.Register(new FooService<DateTime>(), "someServiceId"); ServiceLocator.Register(new FooService<double?>(), "anotherServiceId"); // Retrieve a particular FooService instance and call the Get method var fooService = (FooService<object>)ServiceLocator.Get("someServiceId"); var foo = fooService.Get("someFooId");
I want to use the Get () method in an instance of FooService - no matter what type the selected instance of FooService returns. However, this code raises the following exception:
Cannot pass an object of type "WindowsFormsApplication7.FooService`1 [System.DateTime]" to enter "WindowsFormsApplication7.FooService`1 [System.Object]".
Any suggestions on how to solve this problem would be greatly appreciated.
You could argue why I created a generic set of FooService. However, this is done to ensure type safety in a safe type environment. In this particular case, however, the FooService should be used in the Web API controller to serve various types of Foo. It should return a response with Foo of T without regard for type T.
source share