How do you make a Generic Generic Factory? - c#

I am working on a client (Silverlight) interface to a collection of webmethod. And I am trying to avoid writing any custom code for every webmethod. So I have created a ServiceCall<TResult> to handle each call, TResult specifies the return type of the service (I use XmlSerializer to create the returned instance). The client class exposes a function matching each webmethod, and all that function has to do is to create a new instance of ServiceCall<TResult>, with the TResult specified as the expected return type of the method.
And that works just fine.
I am also using Ninject (dependency injector) to try and keep everything independent. Ninject supports open generics, whichs works out great with my ServiceCall<TResult>.
But it also means that I'm injecting a reference to the Ninject container. Which hides the dependency on ServiceCall<TResult> being bound to the container. So I would like to instead inject a factory for creating my ServiceCall<TResult> instances. Which is not tricky, but I would like to make it a generic generic factory. Meaning I would like to have something like Factory<T<>> which would have a method public T<TU> Createinstance<TU>().
But I have no idea how I could create generic class with a type parameter that is itself an open genric.
Is it event posible in .Net? - Or do I have to create a specific ServiceCallFactory?
Edit:
I am using interfaces for the dependencies, but there's no need to mix them into the question here, so I edited that out of the question.
In responce to Timwi:
The common way to use dependency injection (DI) is to bind an interface to your implementation, only the container knows of these bindings. You then code up against the interfaces instead. This brings a ton of advantages. More than I can mention here.
Anyway it also rules out the static classes (since that would be a dependency on a specific class). Instead I'll instruct the container (Ninject in this case) to always hand me the same instance for the factory interface, in a singleton like behavior.
This rules out the public static class Factory<T> option, because it is static, and if it is not static I would need to now every type of T I'm gonna use, somewhat defeating the purpose of having a generic class.
The suggestion of having a non-generic class with a "totally generic" method (as in I pass in ServiceCall<MyResult> instead of just MyResult), is what more or less what I am doing now (minus the static class part). The Ninject container has an Get method that work like your second suggestion.
The problem with this is two part; firstly it makes my code directly dependent on one container (Ninject), but this is not really that big a problem to me. What does annoy me is that if you look at me Client from the outside, you'll only see a dependency on Ninject. You wont know until you run try to make a call that client needs an implementation of ServiceCall registered with Ninject to work.
But if the Client contructor took a parameter of type Factory>, then it would much clearer.
In any case I would think this would be a common issue, so either there a common solution, or it is not a common issue and I am trying to do something stupid ;)
I am still not that into dependency injection, so that may very well be the case.

Is this what you are looking for: Generic Factory Pattern
namespace GenericFactoryPatternTestApp
{
public class Factory< T >
{
private readonly Dictionary< string, Type > _factoryDictionary = new Dictionary< string, Type >();
public Factory()
{
Type[] types = Assembly.GetAssembly(typeof (T)).GetTypes();
foreach (Type type in types)
{
if (!typeof (T).IsAssignableFrom(type) || type == typeof (T))
{
// Incorrect type
continue;
}
// Add the type
_factoryDictionary.Add(type.Name, type);
}
}
public T Create< V >(params object[] args)
{
return (T) Activator.CreateInstance(_factoryDictionary[typeof (V).Name], args);
}
}
}

So if I understand you right, you’d have a class looking a bit like this:
public static class Factory<T<>>
{
public static T<TU> CreateInstance<TU>() { /* ... */ }
}
and then you’d call it how? Like this?
var myServiceCall = Factory<ServiceCall<>>.CreateInstance<MyResult>();
What stops you from simply declaring the factory like this...
public static class Factory<T>
{
public static T CreateInstance() { /* ... */ }
}
... or this ...
public static class Factory
{
public static T CreateInstance<T>() { /* ... */ }
}
... and then generating your instance like this?
var myServiceCall = Factory<ServiceCall<MyResult>>.CreateInstance();
var myServiceCall = Factory.CreateInstance<ServiceCall<MyResult>>();
I’m sorry if I’m being dumb, but I’d probably need to know how Ninject works and how it allows you to pass in a factory.

Related

Dependency Injection and initialization methods

I read Miško Hevery's Guide: Writing Testable Code and it states a warning sign if an "Object not fully initialized after the constructor finishes (watch out for initialize methods)".
Let's say I wrote a Redis wrapper class that has an init method that accepts hostname and port. This according to Miško, is a warning sign, since I need to call its init method.
The solution I'm contemplating with is the following:
For every class that need this kind of initialization, create a factory class that has a Create method which creates the class, and also call its init method.
Now in code: Instead of using something like:
class Foo
{
private IRedisWrapper _redis;
public Foo(IRedisWrapper redis)
{
_redis = redis;
}
}
....
IRedisWrapper redis = new RedisWrapper();
redis.init("localhost", 1234);
Foo foo = new Foo(redis);
I'd use something like:
class Foo
{
private IRedisWrapper _redis;
public Foo(IRedisWrapper redis)
{
_redis = redis;
}
}
....
RedisWrapperFactory redisFactory = new RedisWrapperFactory();
IRedisWrapper redisWrapper = redisFactory.Create();
Foo foo = new Foo(redisWrapper);
I'm using Simple Injector as an IOC framework, which makes this the above solution probelmatic - in this case I'd use something like:
class Foo
{
private RedisWrapper _redis;
public Foo(IRedisWrapperFactory redisFactory)
{
_redis = redisFactory.Create();
}
}
I'd really like to hear your input on the above solution.
Thanks
Perhaps I misunderstood your question, but I don't think Simple Injector is a limiting factor here. Since constructors should do as little as possible, you shouldn't call the Create method from within your constructor. It's even an odd thing to do, since a factory is meant to delay the creation of a type, but since you call Create inside the constructor the creation is not delayed.
Your Foo constructor should simply depend on IRedisWrapper and you should extract the redisFactory.Create() call to your DI configuration like this:
var redisFactory = new RedisWrapperFactory();
container.Register<IRedisWrapper>(() => redisFactory.Create());
But since the factory's sole purpose is to prevent duplicate initialization logic throughout the application, it now lost its purpose, since the only place the factory is used is within the DI configuration. So you can throw the factory out and write the following registration:
container.Register<IRedisWrapper>(() =>
{
IRedisWrapper redis = new RedisWrapper();
redis.init("localhost", 1234);
return redis;
});
You now placed the body of the Create method inside the anonymous delegate. Your RedisWrapper class currently has a default constructor, so this approach is fine. But if the RedisWrapper starts to get dependencies of its own, it's better to let the container create that instance. This can be done as follows:
container.Register<IRedisWrapper>(() =>
{
var redis = container.GetInstance<RedisWrapper>();
redis.init("localhost", 1234);
return redis;
});
When you need your class to be initialized after creation, as the RedisWrapper clearly needs, the adviced approach is to use the RegisterInitializer method. The last code snippet can written as follows:
container.Register<IRedisWrapper, RedisWrapper>();
container.RegisterInitializer<RedisWrapper>(redis =>
{
redis.init("localhost", 1234);
});
This registers the RedisWrapper to be returned when an IRedisWrapper is requested and that RedisWrapper is initialized with the registered initializer. This registration prevents the hidden call back to the container. This improves performance and improves the ability for the container to diagnose your configuration.
Having RedisWrapperFactory as the dependency doesn't seem quite right, since it's not really the factory you want. Unless of course there were specific parameters that you needed to pass to Create().
I don't know Simple Injector, but I would suggest that if it doesn't allow you to customise the creation of you objects to use your factory, you might want to look at some other DI frameworks. I use StructureMap, but there are others to choose from.
Edit: Having said that, if the contract for IRedisWrapper is that it must be initialised in some specific way after the constructor is called, it will look a little odd if you use it in Foo without calling init(). Especially to someone who is familiar with IRedisWrapper (many people), and not with the IOC setup of that particular application (not many people). Certainly, if you are going to use a factory, as Arghya C has said, use that through an interface too, otherwise you haven't actually achieved anything because you don't get to choose which IRedisWrapper you are injecting.
If your RedisWrapperFactory is defined in some other layer (where it gets data from DB/File/some service), the the code will kill the purpose of dependncy injection. Your layer becomes directly dependent on the other. Also, that is not testable anymore as you cannot create a mock/fake object of that for testing. Obviously you don't want to do real DB operations or I/O read-write or service call in testing.
You might want to do something like...
class Foo
{
private IRedisWrapper _redis;
public Foo(IRedisWrapperFactory redisFactory)
{
_redis = redisFactory.Create();
}
}
In the other layer
public class RedisWrapperFactory : IRedisWrapperFactory
{
public IRedisWrapper Create()
{
var r = RedisWrapper();
r.Init("localhost", 1234); //values coming from elsewhere
return r;
}
}
In your Bootstrapper() or application_Start() method, inject the factory, something like
container.Register<IRedisWrapperFactory, RedisWrapperFactory>();

Is using var + basic dependency factory more loosely coupled than C# interfaces?

This is a general design question. We often use interfaces to decouple components, write to an interface not an implementation etc. Sometimes interfaces are used w/ a basic injection technique, such as,
interface IMyInterface
{
void DoSomething();
}
static class IMyInterfaceFactory
{
public static IMyInterface GetInstance()
{
return new MyInterfaceInstance();
}
}
class IMyInterfaceConsumer
{
IMyInterface mInterface;
public IMyInterfaceConsumer()
{
this.mInterface = IMyInterfaceFactory.GetInstance();
}
public void UseTheInterface()
{
this.mInterface.DoSomething();
}
}
My question is about using the var keyword instead. Not even using a true C# interface, but still creating an 'interface', in the design sense,
static class IMyInterfaceFactory
{
// of course, this doesnt need to be a single instance
static MyInterfaceInstance mSingleInstance;
// no longer programming to the interface, just returning the instance
public static MyInterfaceInstance GetInstance()
{
// null coalesce
return mSingleInstance ?? (mSingleInstance = new MyInterfaceInstance());
}
}
class IMyInterfaceConsumer
{
public void UseTheInterface()
{
// shorthand way, could also omit var, too
var myInterface = IMyInterfaceFactory.GetInstance();
myInterface.DoSomething();
}
}
This way I still only need to change the factory once, and as long as whatever instance it returns supports the methods that need to be consumed, it will work. The advantage however is that the producing and consuming objects dont need to even know about any explicit interface, none exists. It could also cleanly support an interface with more than just a couple methods (prevent bloated interface declarations).
One obvious downside is that everytime you want to consume a method from the 'interface', the factory will potentially have to re-instantiate the class, unless there is a single instance cached (as above) or some memoization technique used.
Pros/cons of this approach? Is this a common practice?
There is nothing dynamic or loose about the var keyword. It triggers static type inference at compile time.
Your second piece of code behaves identically to
public void UseTheInterface()
{
// shorthand way, could also omit var, too
MyInterfaceInstance myInterface = IMyInterfaceFactory.GetInstance();
myInterface.DoSomething();
}
The factory function is still strongly typed. In fact, by removing the interface, you've made consumer code much more tightly coupled.
Var keyword is still technically strongly typed, so your code does know what class/interface it is. If you planned on dumping it into an object then we are saying that the rest of your code has no clue what is coming out of that factory. I wouldn't suggest that though since that causes you to cast that object to utilize anything in it.
I'm not sure where you are trying to go with the "prevent bloated interface declarations" but you could do polymorphism through extending a base class or an abstract class as well. That would make it so any code that is common between the child classes could be left alone and any specific code (methods or properties) for each child class could be overridden.
If you are looking to change out the interface all together you will need to implement an interface in the interface, see this post. So you will basically have interface A only have the method DoStuff() and other interfaces that inherit from this interface could be used polymorphically like you are describing.
interface A
{
DoStuff();
}
interface B : A
{
DoSomethingElse();
}
class C : B
{
DoStuff(){}
DoSomethingElse(){}
}
By the way, your "single instance cached" code above is close to something called a singleton pattern.

c# constructor injection and constructor overloads

I'm using constructor injection for the first time and wish to write my code defensively.
Therefore if I have a class with a constructor and a save method as below:
public SomeConstructor(string name, Object someObject)
{
_name= name;
_someObject= someObject;
}
public void Save()
{
// Does a database save
}
But then need to create another related method in this Class that doesn't need the _someObject so I create an overloaded chained constructor as:
public SomeConstructor(string name) : this(name, null)
{
}
How can I successfully stop someone instantiating the class with this second constructor with 1 parameter and using the Save() which has someObject as null?
I'm not using an injection tool.
Above is a simple example and in it, you are correct I could just throw an exception for a null just as I would if a property was not set.
What I wanted to avoid was a series of validation checks at the start of each method.
Use the friction you are experiencing as a warning system. It's really telling you that you're likely moving towards low cohesion and violation of the Single Responsibility Principle.
If this is the case, refactor the class into two separate classes.
You may prevent that situation with a run-time exception like InvalidOperationException.
If some instantiated the class with the two-parameters-constructor and tries to call Save, just check if "someObject" is null, and if it's so:
throw new InvalidOperationException("This method cannot be invoked in current object state");
In the other hand, if this second constructor would be used by your library and third-party library developers wouldn't be allowed to use it, this constructor should have the internal modifier.
The IoC it is just a way to dinamically resolve the dependency but doens't solve any OO problem.
I would focus on a good OO design instead of try to find a way to cheat the framework forcing to use a contractor instead of another.The question is how would you do that if you were not using an IoC framework?
probabily checking if SomeObject is null?
public void Save()
{
if (_someObject == null)
throw new InvalidOperationException();
}
I guess that this is obvious. But you really can't create a contract in which the type is constructed differently unless you also change your SomeConstructor type to work like a decorator pattern. What the decorator pattern does is that it let's you build the inheritance hierarchy at run-time not compile-time.
You can then create different objects depending on what operations are allowed internally. This is some work for something which can easily be handled with a pre-condition for the Save method. But maybe this is what you need. And if you did it you could stipulate your contract in the constructor of SomeConstructor.
Here's an example:
interface ISomeConstructor
{
void Save();
}
class SomeConstructor
{
ISomeConstructor impl;
public SomeConstructor(string name, object someObject)
{
impl = new StringAndObject(name, someObject);
}
public SomeConstructor(string name)
{
impl = new JustString(name);
}
public void Save()
{
impl.Save();
}
}
The types StringAndObject and JustString implements ISomeConstructor and they can handle the Save method as they see fit.
This is a slight variation of the decorator pattern as normally you'd expect ISomeConstructor to be passed as an argument to the constructor as well.

C# Get a list of all runtime constructed classes of a generic class

I'm trying to make a list of all the runtime constructed classes created by a generic class. In other words, if I have a class:
public GenericCls<T> {
public void Reset() { ... }
...
}
And I have code in various places like this:
GenericCls<int> gci = new GenericCls<int>();
GenericCls<String> gcs = new GenericCls<String>();
GenericCls<float> gcf = new GenericCls<float>();
...
Can I get something like this?:
Type[] allconstructed = GetAllConstructed(typeof(GenericCls<>));
which returns {GenericCls<int>,GenericCls<String>,GenericCls<float>,...}
The use case involves a generic allocator, that supports any type of object allocation (it's like new XXX(), but nicer to the garbage collector). I won't go into specifics, because it will just complicate the question. Basically, I will not know all the constructed classes at compile time, since the library is a dll intended to be used with a separate code project. So I will need some form of reflection that I can't seem to find on the interwebs.
Assembly.GetExecutingAssembly().GetExportedTypes() does not contain anything but the base generic class (i.e. typeof(GenericCls<>))
typeof(GenericCls<>).GetGenericArguments() returns only Type "T", which is not only an invalid type, but entirely useless.
Is it even possible to find all constructed classes of a generic class if you only know the generic class' type? (typeof(GenericCls<>);) I'm not sure if "constructed" is the right word - I want to know either all the concrete generic-derived classes currently active, or all of these that will ever exist (not sure how C# handles generic construction behind the scenes).
#David Mårtensson: Your answer gave me an idea. I could make a static list of types in any non-generic class, and register each constructed class as it was constructed (when T is known).
i.e.
static public class ConcreteList {
static public List<Type> concrete;
}
public class GenericCls<T> {
static GenericCls() {
ConcreteList.concrete.Add(typeof(GenericCls<T>));
}
}
I checked it with ConcreteList.concrete[x].GetGenericArguments(), and it's working. Oh snap.
You might use a factory class to create instances, that way the factory class could keep a list of all created classes.

How can you require a constructor with no parameters for types implementing an interface?

Is there a way?
I need all types that implement a specific interface to have a parameterless constructor, can it be done?
I am developing the base code for other developers in my company to use in a specific project.
There's a proccess which will create instances of types (in different threads) that perform certain tasks, and I need those types to follow a specific contract (ergo, the interface).
The interface will be internal to the assembly
If you have a suggestion for this scenario without interfaces, I'll gladly take it into consideration...
Not to be too blunt, but you've misunderstood the purpose of interfaces.
An interface means that several people can implement it in their own classes, and then pass instances of those classes to other classes to be used. Creation creates an unnecessary strong coupling.
It sounds like you really need some kind of registration system, either to have people register instances of usable classes that implement the interface, or of factories that can create said items upon request.
You can use type parameter constraint
interface ITest<T> where T: new()
{
//...
}
class Test: ITest<Test>
{
//...
}
Juan Manuel said:
that's one of the reasons I don't understand why it cannot be a part of the contract in the interface
It's an indirect mechanism. The generic allows you to "cheat" and send type information along with the interface. The critical thing to remember here is that the constraint isn't on the interface that you are working with directly. It's not a constraint on the interface itself, but on some other type that will "ride along" on the interface. This is the best explanation I can offer, I'm afraid.
By way of illustration of this fact, I'll point out a hole that I have noticed in aku's code. It's possible to write a class that would compile fine but fail at runtime when you try to instantiate it:
public class Something : ITest<String>
{
private Something() { }
}
Something derives from ITest<T>, but implements no parameterless constructor. It will compile fine, because String does implement a parameterless constructor. Again, the constraint is on T, and therefore String, rather than ITest or Something. Since the constraint on T is satisfied, this will compile. But it will fail at runtime.
To prevent some instances of this problem, you need to add another constraint to T, as below:
public interface ITest<T>
where T : ITest<T>, new()
{
}
Note the new constraint: T : ITest<T>. This constraint specifies that what you pass into the argument parameter of ITest<T> must also derive from ITest<T>.
Even so this will not prevent all cases of the hole. The code below will compile fine, because A has a parameterless constructor. But since B's parameterless constructor is private, instantiating B with your process will fail at runtime.
public class A : ITest<A>
{
}
public class B : ITest<A>
{
private B() { }
}
Juan,
Unfortunately there is no way to get around this in a strongly typed language. You won't be able to ensure at compile time that the classes will be able to be instantiated by your Activator-based code.
(ed: removed an erroneous alternative solution)
The reason is that, unfortunately, it's not possible to use interfaces, abstract classes, or virtual methods in combination with either constructors or static methods. The short reason is that the former contain no explicit type information, and the latter require explicit type information.
Constructors and static methods must have explicit (right there in the code) type information available at the time of the call. This is required because there is no instance of the class involved which can be queried by the runtime to obtain the underlying type, which the runtime needs to determine which actual concrete method to call.
The entire point of an interface, abstract class, or virtual method is to be able to make a function call without explicit type information, and this is enabled by the fact that there is an instance being referenced, which has "hidden" type information not directly available to the calling code. So these two mechanisms are quite simply mutually exclusive. They can't be used together because when you mix them, you end up with no concrete type information at all anywhere, which means the runtime has no idea where to find the function you're asking it to call.
So you need a thing that can create instances of an unknown type that implements an interface. You've got basically three options: a factory object, a Type object, or a delegate. Here's the givens:
public interface IInterface
{
void DoSomething();
}
public class Foo : IInterface
{
public void DoSomething() { /* whatever */ }
}
Using Type is pretty ugly, but makes sense in some scenarios:
public IInterface CreateUsingType(Type thingThatCreates)
{
ConstructorInfo constructor = thingThatCreates.GetConstructor(Type.EmptyTypes);
return (IInterface)constructor.Invoke(new object[0]);
}
public void Test()
{
IInterface thing = CreateUsingType(typeof(Foo));
}
The biggest problem with it, is that at compile time, you have no guarantee that Foo actually has a default constructor. Also, reflection is a bit slow if this happens to be performance critical code.
The most common solution is to use a factory:
public interface IFactory
{
IInterface Create();
}
public class Factory<T> where T : IInterface, new()
{
public IInterface Create() { return new T(); }
}
public IInterface CreateUsingFactory(IFactory factory)
{
return factory.Create();
}
public void Test()
{
IInterface thing = CreateUsingFactory(new Factory<Foo>());
}
In the above, IFactory is what really matters. Factory is just a convenience class for classes that do provide a default constructor. This is the simplest and often best solution.
The third currently-uncommon-but-likely-to-become-more-common solution is using a delegate:
public IInterface CreateUsingDelegate(Func<IInterface> createCallback)
{
return createCallback();
}
public void Test()
{
IInterface thing = CreateUsingDelegate(() => new Foo());
}
The advantage here is that the code is short and simple, can work with any method of construction, and (with closures) lets you easily pass along additional data needed to construct the objects.
Call a RegisterType method with the type, and constrain it using generics. Then, instead of walking assemblies to find ITest implementors, just store them and create from there.
void RegisterType<T>() where T:ITest, new() {
}
I don't think so.
You also can't use an abstract class for this.
I would like to remind everyone that:
Writing attributes in .NET is easy
Writing static analysis tools in .NET that ensure conformance with company standards is easy
Writing a tool to grab all concrete classes that implement a certain interface/have an attribute and verifying that it has a parameterless constructor takes about 5 mins of coding effort. You add it to your post-build step and now you have a framework for whatever other static analyses you need to perform.
The language, the compiler, the IDE, your brain - they're all tools. Use them!
No you can't do that. Maybe for your situation a factory interface would be helpful? Something like:
interface FooFactory {
Foo createInstance();
}
For every implementation of Foo you create an instance of FooFactory that knows how to create it.
You do not need a parameterless constructor for the Activator to instantiate your class. You can have a parameterized constructor and pass all the parameters from the Activator. Check out MSDN on this.

Categories

Resources