I'm trying to create a function in C# which will allow me to, when called, return a reference to a given class type. The only types of functions like this that I have seen are in UnrealScript and even then the functionality is hard coded into its compiler. I'm wondering if I can do this in C#. Here's what I mean (code snippet from UnrealScript source):
native(278) final function actor Spawn
(
class<actor> SpawnClass,
optional actor SpawnOwner,
optional name SpawnTag,
optional vector SpawnLocation,
optional rotator SpawnRotation
);
Now in UScript you would call it like this...
local ActorChild myChildRef; //Ref to ActorChild which Extends 'actor'
myChildRef = Spawn(class'ActorChild' ...); //rest of parameters taken out
myChildRef.ChildMethod(); //method call to method existing inside class 'ActorChild'
Which will return a reference to an object of class 'ActorChild' and set it to variable 'myChildRef.' I need to do something similar within C#.
I've looked into Generics but it seems that to use them, I need create an instace of the class where my function lies and pass the 'generic' parameter to it. This isn't very desirable however as I won't need to use the 'Spawn' function for certain classes but I would still need to add the generic parameter to the class whenever I use it.
I guess a simplified question would be, how can I return a type that I do not know at compile time and when the different classes could be far too many to trap.
Pseudo-Code (sticking to UScript class names, i.e. Actor):
//Function Sig
public class<Actor> Create(class<Actor> CreatedClass)
{
return new CreatedClass;
}
//Function call
ActorChild myChild = Create(class'ActorChild');
Any ideas?
EDIT: I would like to avoid explicit typecasts that would occur from the class calling Created. If I can typecast to the desired object within the Created method and return the 'unknown type' whatever that may be, I would be extremely happy.
EDIT 2: Thanks for your answers.
Rather than use a generic class, use a generic method:
public T Spawn<T>() where T : new()
{
return new T();
}
Having said that, I assume you want to do more than just blindly create an instance, otherwise you could just call new MyClass() yourself.
You can use the class System.Type to represent classes. To get references to type objects, you either use typeof (in a scope where the class is actually defined)
System.Type t = typeof(ActorChild);
or the Type.GetType function (if you only know the name of the type)
System.Type t = Type.GetType("NamespaceFoo.ActorChild");
You can then use the reflection API to create an instance
public object Create(System.Type ClassToCreate)
{
return ClassToCreate.GetConstructor(Type.EmptyTypes).Invoke(null);
}
What you're trying to accomplish can be done quite easily with Reflection and something called Dynamic Method Invocation.
Basically, you'll be using the Type object, the Activator.CreateInstance Method and some other nice classes like MethodInfo and ParameterInfo.
Here's an example to get you started:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace Reflection
{
class SomeClass
{
private string StringPrimer = "The parameter text is: ";
public SomeClass(string text)
{
Console.WriteLine(StringPrimer + text);
}
public string getPrimer() //supplies the Primer in upper case, just for kicks
{
return StringPrimer.ToUpper();
}
}
class Program
{
static void Main(string[] args)
{
SomeClass s = new SomeClass("this is an example of the classes normal hard-coded function.\nNow try feeding in some text");
string t = Console.ReadLine();
Console.WriteLine("Now feed in the class name (SomeClass in this case)");
Type myType = Type.GetType("Reflection."+Console.ReadLine()); //Stores info about the class.
object myClass = Activator.CreateInstance(myType, new object[] { t }); //This dynamically calls SomeClass and sends in the text you enter as a parameter
//Now lets get the string primer, using the getPrimer function, dynamically
string primer = (string)myType.InvokeMember("getPrimer",
BindingFlags.InvokeMethod | BindingFlags.Default,
null,
myClass,
null); //This method takes the name of the method, some Binding flags,
//a binder object that I left null,
//the object that the method will be called from (would have been null if the method was static)
//and an object array of parameters, just like in the CreateInstance method.
Console.WriteLine(primer);
}
}
}
Related
I am in a situation where i have to inherit a class and access its protected method to get a value.
Due to some weird situations i have most of my code in reflection and i m hoping if i have any chance to get this working using reflection.
To make things more clear,
Below is the class
public class Converter: BaseConverter
{
public Converter();
protected override object StringToValue();
}
I need to do below to get the functionality working.
public class myclass:Converter
{
public StringToValue()
{
base.StringToVaue();
}
}
However I cannot use direct reference of Converter dll in my project . So i am handicapped here to use inheritance and myclass : converter. So how can i approach this using reflection which would be to basically make myclass inherit the converter class at runtime. I am not sure if it makes sense or not however it seems to me that its where i am trying to head towards to get an answer
You can use TypeBuilder to create a whole new type at runtime via reflection. Of course ultimately you need a reference to the assembly which contains Converter to inherent from it. Make sure to check out the MSDN example of TypeBuidler. You need to call ModuleBuilder.DefineType() which has an overload to specify the parent type.
But if you go that way you have to do everything with reflection including emitting the methods. I don't fully understand your restrictions so that's the best answer I could think of but I don't really like it ;)
While we're talking about hacking: Do you really need to inherit from Converter or do you only need to access its methods? In case you only need the methods you could simply hold an instance of Converter as an attribute of type object and call the protected method via refletion inside your public StringToValue method.
EDIT:
As you ask for sample code. With reflection you can bypass the class security mechanism of C#, which means you're able to call non-public methods on any object. First you need the Type. Because you can't write it out in C# you need to get it some other way. Then you can create an instance of that type with Activator. You also need to obtain information about the method you want to call. It makes sense to cache this information because the processes of reading that information with reflection is kinda slow. Finally you can use the MethodInfo to actually call the method.
I haven't tested that code because I don't have a machine to do so right now.
class myclass
{
object internalConverter;
MethodInfo converterStringToValueMethod;
public myclass()
{
// Here you need a reference to the assembly which contains the Converter type
Assembly asm = Assembly.Load("xxx.dll"); // Name of the assembly which contains Converter
Type converterType = asm.GetType("Converter");
this.internalConverter = Activator.CreateInstance(converterType);
this.converterStringToValueMethod = converterType.GetMethod("StringToValue", BindingFlags.NonPublic | BindingFlags.Instance);
}
public object StringToValue()
{
return converterStringToValueMethod.Invoke(internalConverter, null);
}
}
This should do what you want without inheritance:
using System;
using System.Reflection;
namespace Test
{
class Converter
{
string Value;
public Converter(string test)
{
Value = test;
}
protected object StringToValue()
{
return Value;
}
}
class myclass
{
object Unknown;
public myclass(object other)
{
Unknown = other;
}
MethodInfo originalFunction;
public object StringToValue()
{
if (originalFunction == null)
{
originalFunction = Unknown.GetType().GetMethod("StringToValue", BindingFlags.NonPublic | BindingFlags.Instance);
}
return originalFunction.Invoke(Unknown, null);
}
}
class Test
{
[System.STAThread]
public static void Main(string[] args)
{
Converter unknown = new Converter("TEST");
myclass mine = new myclass(unknown);
Console.WriteLine(mine.StringToValue());
Console.ReadLine();
}
}
}
This is a bad idea for a number of reasons, but if you are sure it is what you need...
Consider following code:
public class Test
{
[System.AttributeUsage(System.AttributeTargets.Method)]
class MethodAttribute : System.Attribute
{
public MethodAttribute(System.Reflection.MethodInfo methodInfo)
{
}
}
public void Foo()
{
}
[Method(Test.Foo)] //< THIS IS THE IMPORTANT LINE
public void Boo()
{
}
}
I want to store MethodInfo instance of Foo in attribute of Boo, but problem is, that I cannot use Foo nor Test.Foo to get instance of MethodInfo. I can NOT use typeof(Test).GetMethod("Foo") (not my decision).
Important information:
Generated error is: error CS0120: An object reference is required to access non-static member `Test.Foo()'
I'm coding in Unity3D which is using Mono, not .Net. (more info http://docs.unity3d.com/410/Documentation/ScriptReference/MonoCompatibility.html )
Windows 7
Absolutely unimportant information:
Why I cannot use typeof(Test).GetMethod("Foo"): I'm not allowed. It's not in my power to change this decision. I can not. (Also, personally, I would like to avoid it anyway as it needs to do some lookup instead of getting statically the data. Also it won't be changed automatically during refactoring and will be checking run-time, not compile-time.)
Why I want to do this: later in code, I want to create a delegate of Boo() (this time normally, with an instance) and use in special even system or something. Before it's called, this attribute allows to setup method to be called in prepare for main event (it's optional, it can be null) and I know how to create a delegate when I have an object and a method info.
Why I cannot just provide both delegates when registering or something: because class containing these methods is not always the one who registers to event source, I need to keep the registration code as simple as possible. In other words, I want to avoid situation when person writing method responsible for connecting forgots to add this preparation delegate.
use expression :
static public class Metadata<T>
{
static public PropertyInfo Property<TProperty>(Expression<Func<T, TProperty>> property)
{
var expression = property.Body as MemberExpression;
return expression.Member as PropertyInfo;
}
}
var foo = Metadata<Test>.Property(test => test.Foo);
I have a dynamic variable
dynamic d = GetSomeObject();
Sometime , in future, a user send me a function to execute ( its name) e.g "UsersGetAll"
So I need to do something like : d.UsersGetAll()
I can do it with reflection. But I want to use the DLR .
Does the only solution of doing this is to have MyObject inherit from DynamicObject and then implement TryInvokeMember?
What if I don't have control over the class ?
As Jon notes, the following really only applies if you suspect that the type is providing the method at runtime via the DLR; in most simple cases, reflection will be easier.
dynamic is intended when you know the method name but not the target. If you don't know the method name it is tricker. The tricky bit, perhaps, is ensuring you keep the call-site so that it can be re-used (which is how the DLR maintains performance). One cheeky way would be a static utility class that keeps track of invoked methods. Here's an example - note that it gets much messier if you need to handle parameters:
using Microsoft.CSharp.RuntimeBinder;
using System;
using System.Collections;
using System.Runtime.CompilerServices;
public class Foo
{
public object Bar() { return "I was here"; }
}
static class Program
{
static void Main()
{
object obj = new Foo();
object result = DynamicCallWrapper.Invoke(obj, "Bar");
Console.WriteLine(result);
}
}
static class DynamicCallWrapper
{
// Hashtable has nice threading semantics
private static readonly Hashtable cache = new Hashtable();
public static object Invoke(object target, string methodName)
{
object found = cache[methodName];
if (found == null)
{
lock (cache)
{
found = cache[methodName];
if(found == null)
{
cache[methodName] = found = CreateCallSite(methodName);
}
}
}
var callsite = (CallSite<Func<CallSite, object,object>>)found;
return callsite.Target(callsite, target);
}
static object CreateCallSite(string methodName)
{
return CallSite<Func<CallSite, object, object>>.Create(
Binder.InvokeMember(
CSharpBinderFlags.None, methodName, null, typeof(object),
new CSharpArgumentInfo[] {
CSharpArgumentInfo.Create(
CSharpArgumentInfoFlags.None, null) }));
}
}
I can do it with reflection. But I want to use the DLR.
Why? Assuming this is a "normal" object which isn't actually going to respond dynamically, reflection is going to be the easiest approach here.
The dynamic feature in C# 4 (in terms of the language feature) does absolutely nothing to help you here. It only allows dynamic binding of member names within C# source code.
Now you could:
Start an IronPython session, and create a tiny Python script to call the method using dynamic binding.
Use CSharpCodeProvider to compile some C# code using dynamic with the relevant method name, then execute that code.
Look at the generated code for your d.UsersGetAll() call, and basically emulate that.
All of these options are likely to be harder than reflection, if all you want it so call a "normal" method on a "normal" object, and you happen to only know the name at execution time.
First of all, I want to point out, that I already have a working solution, but I am trying to see if there is a way to make the code cleaner and less cumbersome.
Here is my situation. I have actually simplified the situation and created a fake example to make the illustration clear. I am just going to lay out a concrete example showing what I have already done, and it works.
Suppose we have these classes:
public abstract class Shape{ //...elided... }
public class Square : Shape { //...elided... }
public class Circle : Shape { //...elided... }
And suppose there's some kind of class that does something with them like this:
public class ShapeThingy
{
public static void MakeSquaresDance(List<Squares> squares){ //...elided... }
public static void RollCircles(List<Circles> circles){ //...elided... }
}
Now suppose I want to test the ShapeThingy class. Suppose that for some of the tests, I want to substitute MockSquares and MockCircles into the lists in place of Squares and Circles. Also, suppose that setting up the MockCircles and the MockSquares is very similar, such that I want to have one method to create the lists of mock shapes, and I tell this method the type of shape that I need. Here is how I have implemented it:
public class Tests
{
[Test]
public void TestDancingSquares()
{
List<Squares> mockSquares = GetMockShapes<Square, MockSquare>();
ShapeThingy.MakeSquaresDance(mockSquares);
Assert.Something();
}
[Test]
public void TestRollingCircles()
{
List<Circles> mockCircles = GetMockShapes<Circle, MockCircle>();
ShapeThingy.RollCircles(mockCircles );
Assert.Something();
}
private List<TBase> GetMockShapes<TBase, TMock>()
where TBase : Shape
where TMock : TBase, new()
{
List<TBase> mockShapes = new List<TBase>();
for (int i = 0; i < 5; i++)
{
mockShapes.Add(MockShapeFactory.CreateMockShape<TMock>());
}
}
}
public class MockSquare : Square { //...elided... }
public class MockCircle : Circle { //...elided... }
public class MockShapeFactory
{
public static T CreateMockShape<T>()
where T : Shape, new()
{
T mockShape = new T();
//do some kind of set up
return mockShape;
}
}
Now this works fine. The problem I have with it is that you have specify to GetMockShapes() both the desired output type of the list, and the mock type that you actually want the list to contain. When in reality, I already know that if I ask GetMockShapes() for List<Square>, then it should actually be filled with MockSquare. It's kind of cumbersome to have to specify both things over and over.
What I want to do is something like this:
private List<TBase> GetMockShapes<TBase>()
where TBase : Shape
{
List<TBase> mockShapes = new List<TBase>();
Type mockType = getAppropriateMockType<TBase>();
for (int i = 0; i < 5; i++)
{
//compiler error: typeof(mockType) doesn't work here
mockShapes.Add(MockShapeFactory.CreateMockShape<typeof(mockType)>());
}
}
private Type getAppropriateMockType<TBase>()
{
if(typeof(TBase).Equals(typeof(Square)))
{
return typeof(MockSquare);
}
if(typeof(TBase).Equals(typeof(Circle)))
{
return typeof(MockCircle);
}
//else
throw new ArgumentException(typeof(TBase).ToString() + " cannot be converted to a mock shape type.");
}
//add then a test would look like this
//(one less word, one less chance to screw up)
[Test]
public void TestDancingSquares()
{
List<Squares> mockSquares = GetMockShapes<Square>();
ShapeThingy.MakeSquaresDance(mockSquares);
Assert.Something();
}
The problem is that version won't compile, and I can't figure out a way around it. Maybe what I want to do is not possible.
Now at this point you may be thinking, "If he just uses IEnumerable<T> instead of List<T>, then he can take advantage of covariance in C# 4.0 and he won't have to do any of this crap," which is true, but but in our real code, we are not using List<T>, but rather a custom concrete type, Something<T> (and it is not an IEnumerable-style collection), and I don't have the ability to change the usage of Something<T> and introduce a covariant interface ISomething<out T> right now.
Anyways, all I am trying to do, I guess, is trying to save myself from having to type one extra word whenever I call GetMockShapes(), so it's not really that big of a deal, and I dunno, maybe it's good that both types are specified so that it's plain to see. I just thought it would be cool if I could figure out some way to do this, and I would learn something new as well. I mostly want to know if this can be done to satisfy my curiosity. I don't think it's really that important in terms of code quality.
Okay the problem now is that you can't invoke a generic with a Type instance, you need a compile-time type handle for that.
To get around this you can:
Modify the MockShapeFactory.CreateMockShape<T> method to take a Type instance rather than write it as generic - but the actual creation of the instance would probably be harder then.
Dynamically bind to the 'correct' version of the CreateMockShape method (based on the type returned from getAppropriateMockType) using reflection.
For the second - this test code might prove helpful:
#region some stubs (replaced with your types)
public class Shape { }
public class MockSquare : Shape { }
public class MockCircle : Shape { }
public class MockShapeFactory
{
//I've added a constraint so I can new the instance
public static T CreateMockShape<T>()
where T : Shape, new()
{
Console.WriteLine("Creating instance of {0}", typeof(T).FullName);
return new T();
}
}
#endregion
//you can cache the reflected generic method
System.Reflection.MethodInfo CreateMethodBase =
typeof(MockShapeFactory).GetMethod(
"CreateMockShape",
System.Reflection.BindingFlags.Public
| System.Reflection.BindingFlags.Static
);
[TestMethod]
public void TestDynamicGenericBind()
{
//the DynamicBindAndInvoke method becomes your replacement for the
//MockShapeFactory.CreateMockShape<typeof(mockType)>() call
//And you would pass the 'mockType' parameter that you get from
//getAppropriateMockType<TBase>();
Assert.IsInstanceOfType
(DynamicBindAndInvoke(typeof(MockCircle)), typeof(MockCircle));
Assert.IsInstanceOfType
(DynamicBindAndInvoke(typeof(MockSquare)), typeof(MockSquare));
}
//can change the base type here according to your generic
//but you will need to do a cast e.g. <
public Shape DynamicBindAndInvoke(Type runtimeType)
{
//make a version of the generic, strongly typed for runtimeType
var toInvoke = CreateMethodBase.MakeGenericMethod(runtimeType);
//should actually throw an exception here.
return (Shape)toInvoke.Invoke(null, null);
}
It looks worse than it is - the goal is to replace the call to the factory's generic method with one that accepts a Type instance - which is what DynamicBindAndInvoke(Type) does in this example. It might look pointless in this test - but that's only because I'm feeding in types known at compile time - in your case the type being passed would be the one retrieved from your getAppropriateMockType method.
Note that I've assumed that your factory method is a static on MockShapeFactory here. If it's not, then the reflection and invoke code would have to change to search for an instance method and to pass the instance of the factory as the first parameter to Invoke.
This pattern can be extended to compile delegates, thus speeding it all up, but for a test environment that kind of optimisiation is probably pointless.
I'm not sure it's a very good way to do things, but I got the GetMockShapes method working the way you were looking for. The idea is to start with the MockShapeFactory, get its CreateMockShape method, convert it to the appropriate generic version and invoke it to create an object of the correct type.
That gets an object though, and mockShapes's Add method only accepts the correctly typed Shape. I couldn't figure out how to dynamically cast the new mockShape to its appropriate type. That would have avoided the need to invoke the builder through reflection anyway, I think.
I circumvented the type checking system instead (like I said, "not sure it's a very good way to do things"). I started with the mockShapes list, got its runtime type, got its Add method, and invoked that with the newly created object. The compiler expects objects for the method and allows this; reflection enforces proper typing at runtime. Bad things might happen if GetAppropriateMockType ever returns an inappropriate type.
using System.Collections.Generic;
using System.Reflection;
using System;
private List<TBase> GetMockShapes<TBase>()
where TBase : Shape
{
Type TMock = getAppropriateMockType<TBase>();
// Sanity check -- if this fails, bad things might happen.
Assert(typeof(TBase).IsAssignableFrom(TMock));
List<TBase> mockShapes = new List<TBase>();
// Find MockShapeFactory.CreateMockShape() method
MethodInfo shapeCreator = typeof(MockShapeFactory).GetMethod("CreateMockShape");
// Convert to CreateMockShape<TMock>() method
shapeCreator = shapeCreator.MakeGenericMethod(new Type[] { TMock });
for (int i = 0; i < 5; i++)
{
// Invoke the method to get a generic object
// The object to invoke on is null because the method is static
// The parameter array is null because the method expects no parameters
object mockShape = shapeCreator.Invoke(null, null);
mockShapes.GetType() // Get the type of mockShapes
.GetMethod("Add") // Get its Add method
.Invoke( // Invoke the method
mockShapes, // on mockShapes list
new object[] { mockShape }); // with mockShape as argument.
}
return mockShapes;
}
A better (but situation-specific) way
After some more thinking I realized there's an unstated assumption here you can abuse. You're trying to make a List<TBase> and fill it with TMock. The whole point of TMock is to impersonate TBase, so TMock is a TBase. In fact, the List even uses TBase as its type parameter.
That's important because it means you don't have to cast the generic object to a TMock, you can just cast it to a TBase. Since TBase is known at compile time, you can use a simple static cast instead of circumventing the typing system to pass a generic object to a typed method. I think this way is a lot better if you can use it.
using System.Collections.Generic;
using System.Reflection;
using System;
private List<TBase> GetMockShapes<TBase>()
where TBase : Shape
{
Type TMock = getAppropriateMockType<TBase>();
// Sanity check -- if this fails, bad things might happen.
Assert(typeof(TBase).IsAssignableFrom(TMock));
List<TBase> mockShapes = new List<TBase>();
// Find MockShapeFactory.CreateMockShape() method
MethodInfo shapeCreator = typeof(MockShapeFactory).GetMethod("CreateMockShape");
// Convert to CreateMockShape<mockType>() method
shapeCreator = shapeCreator.MakeGenericMethod(new Type[] { TMock });
for (int i = 0; i < 5; i++)
{
// Invoke the method to get a generic object
// The object to invoke on is null because the method is static
// The parameter array is null because the method expects no parameters
object mockShape = shapeCreator.Invoke(null, null);
//
// Changes start here
//
// Static cast the mock shape to the type it's impersonating
TBase mockBase = (TBase)mockShape;
// Now this works because typeof(mockBase) is known at compile time.
mockShapes.Add(mockBase);
}
return mockShapes;
}
I have a list of class names and methods that can only be read during runtime. Is it possible to create a class dynamically like that? I'm currently using C# 4.0.
It is a little unclear whether you want to define a type at runtime and define methods against it, or whether you want to create an instance of an already-written type, and call methods on it.
Fortunately both are possible.
The second scenario is more likely, so you'd want to look at reflection (below) - but note that there are performance penalties associate with this (and small things like "what arguments does the method take" become very important).
For the first scenario, you'd need to look at TypeBuilder, but that is much more complex. Another option would be CSharpCodeProvider and dynamic assembly loading, but again - not trivial by any stretch.
using System;
namespace MyNamespace {
public class Foo {
public void Bar() {
Console.WriteLine("Foo.Bar called");
}
}
}
class Program {
static void Main() {
string className = "MyNamespace.Foo, MyAssemblyName",
methodName = "Bar";
Type type = Type.GetType(className);
object obj = Activator.CreateInstance(type);
type.GetMethod(methodName).Invoke(obj, null);
}
}
To include parameters (comments) you pass an object[] instead of the null:
using System;
namespace MyNamespace {
public class Foo {
public void Bar(string value) {
Console.WriteLine("Foo.Bar called: " + value);
}
}
}
class Program {
static void Main() {
string className = "MyNamespace.Foo, MyAssemblyName",
methodName = "Bar";
Type type = Type.GetType(className);
object obj = Activator.CreateInstance(type);
object[] args = { "hello, world" };
type.GetMethod(methodName).Invoke(obj, args);
}
}
If you are doing this lots (for the same method) there is a way to improve performance via a typed delegate, but this doesn't gain you much for occasional calls.
You can use the IL emit functionality straight out of the .Net framework to accomplish this. You will need to learn IL in order to dynamically generate type information at runtime--this is not for the feint of heart.
Introduction to Creating Dynamic Types with System.Reflection.Emit
As I can't really answer that you are asking I will answer a number of question you might want to ask.
Can I create an instance of class and call its method where both class and method are specified at run time?
Sure. The simple way first. Use a if statements:
var className = "MyClass";
var methodName = "MyMethod";
if (className == typeof(MyClass).Name) {
var instance = new MyClass();
if (methodName == "MyMethod")
instance.MyMethod();
if (methodName == "MyOtherMethod")
instance.MyOtherMethod();
}
Alternatively, you can use Activator.CreateInstance to create an instance of a class for you.
var className = "MyClass";
var methodName = "MyMethod";
//Get a reference to the Assembly that has the desired class. Assume that all classes that we dynamically invoke are in the same assembly as MyClass.
var assembly = typeof(MyClass).Assembly;
//Find the type that we want to create
var type = assembly.GetTypes().FirstOrDefault(t=>t.Name == className);
if(type != null) {
//Create an instance of this type.
var instance = Activator.CreateInstance(type);
//Find the method and call it.
instance.GetType().GetMethod(methodName).Invoke(instance);
}
Can I generate a class at run time?
Yes you can but it's hard. If you are an experienced C# programmer, know a bit of C++ and assembly, you should be able to grock it. If not, don't bother.
Microsoft provides a library to emit Intermediate Language code called, surpose, IL.Emit. There are very few problems that warrant using this method, amongst those are mock object generation and some aspects of Dependency Injection. It is quite likely that your problem is better solved in another fashion.