Take the following class as an example:
class Sometype
{
int someValue;
public Sometype(int someValue)
{
this.someValue = someValue;
}
}
I then want to create an instance of this type using reflection:
Type t = typeof(Sometype);
object o = Activator.CreateInstance(t);
Normally this will work, however because SomeType has not defined a parameterless constructor, the call to Activator.CreateInstance will throw an exception of type MissingMethodException with the message "No parameterless constructor defined for this object." Is there an alternative way to still create an instance of this type? It'd be kinda sucky to add parameterless constructors to all my classes.
I originally posted this answer here, but here is a reprint since this isn't the exact same question but has the same answer:
FormatterServices.GetUninitializedObject() will create an instance without calling a constructor. I found this class by using Reflector and digging through some of the core .Net serialization classes.
I tested it using the sample code below and it looks like it works great:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Runtime.Serialization;
namespace NoConstructorThingy
{
class Program
{
static void Main(string[] args)
{
MyClass myClass = (MyClass)FormatterServices.GetUninitializedObject(typeof(MyClass)); //does not call ctor
myClass.One = 1;
Console.WriteLine(myClass.One); //write "1"
Console.ReadKey();
}
}
public class MyClass
{
public MyClass()
{
Console.WriteLine("MyClass ctor called.");
}
public int One
{
get;
set;
}
}
}
Use this overload of the CreateInstance method:
public static Object CreateInstance(
Type type,
params Object[] args
)
Creates an instance of the specified
type using the constructor that best
matches the specified parameters.
See: http://msdn.microsoft.com/en-us/library/wcxyzt4d.aspx
When I benchmarked performance of (T)FormatterServices.GetUninitializedObject(typeof(T)) it was slower. At the same time compiled expressions would give you great speed improvements though they work only for types with default constructor. I took a hybrid approach:
public static class New<T>
{
public static readonly Func<T> Instance = Creator();
static Func<T> Creator()
{
Type t = typeof(T);
if (t == typeof(string))
return Expression.Lambda<Func<T>>(Expression.Constant(string.Empty)).Compile();
if (t.HasDefaultConstructor())
return Expression.Lambda<Func<T>>(Expression.New(t)).Compile();
return () => (T)FormatterServices.GetUninitializedObject(t);
}
}
public static bool HasDefaultConstructor(this Type t)
{
return t.IsValueType || t.GetConstructor(Type.EmptyTypes) != null;
}
This means the create expression is effectively cached and incurs penalty only the first time the type is loaded. Will handle value types too in an efficient manner.
Call it:
MyType me = New<MyType>.Instance();
Note that (T)FormatterServices.GetUninitializedObject(t) will fail for string. Hence special handling for string is in place to return empty string.
Good answers but unusable on the dot net compact framework. Here is a solution that will work on CF.Net...
class Test
{
int _myInt;
public Test(int myInt)
{
_myInt = myInt;
}
public override string ToString()
{
return "My int = " + _myInt.ToString();
}
}
class Program
{
static void Main(string[] args)
{
var ctor = typeof(Test).GetConstructor(new Type[] { typeof(int) });
var obj = ctor.Invoke(new object[] { 10 });
Console.WriteLine(obj);
}
}
Related
I get my variable from var pi = propertyInfo.GetValue(instance)
this is an object Type. I know all result of this are of type
ObjectSet<TEntity> . I don't know TEntity. TEntity is allways different.
The consuming function looks alike:
BuildClassItem<T>(ObjectSet<T> entities, ... ) where T : class
How can I cast object to ObjectSet ?
I tried alredy this. But I don't know T
public static ObjectSet<T> MyConvert<T>(object myInput) where T : class
{
return (ObjectSet<T>)myInput;
}
You can use System.Linq.Expressions to construct a "trampoline" - a call into a method which is generic. Once you're inside that generic method, then you can start using T naturally when you need to talk about the type. Here I'm using BuildClassItem directly as the target for the trampoline:
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace Exercise
{
class Program
{
static void Main(string[] args)
{
var obj = GetObjectSet();
//We know obj is an ObjectSet<T> for unknown T
var t = obj.GetType().GetGenericArguments()[0];
var parm = Expression.Parameter(typeof(object));
var objectSet = typeof(ObjectSet<>).MakeGenericType(t);
var method = typeof(Program).GetMethod("BuildClassItem", BindingFlags.Static | BindingFlags.NonPublic).MakeGenericMethod(t);
var trampoline = Expression.Lambda(
Expression.Call(null, method, Expression.Convert(parm,objectSet)), new[] {parm});
var dele = (Action<object>) trampoline.Compile();
dele(obj);
Console.WriteLine("Done");
Console.ReadLine();
}
static void BuildClassItem<T>(ObjectSet<T> entities) where T : class
{
Console.WriteLine("We made it!");
}
static object GetObjectSet()
{
return new ObjectSet<string>();
}
}
internal class ObjectSet<T> where T:class
{
}
}
If you have more work to do between finding the type T and calling BuildClassItem you'd still want to put all of that logic inside a generic method in T and construct a void call into it. You can't "say" the name of the type from outside a generic method so you have no way of storing the returned value from your MyConvert function in a correctly typed variable. So you need to move all of the logic into it.
public class ObjectSet<T>
{
}
public static ObjectSet<T> MyConvert<T>(object myInput) where T : class
{
return (ObjectSet<T>)myInput;
}
invoke like this :
ObjectSet<object> get = MyConvert<object>(new ObjectSet<object>());
I'm not got any error , So what error for your case ??
or
public class FOO
{
}
public interface IObjectSet
{
}
public class ObjectSet<T> : IObjectSet
{
}
IObjectSet get = MyConvert<FOO>(new ObjectSet<FOO>());
I am trying to create a Generic interface where the parameter type of one of the methods is defined by the generic
EDIT
I've changed the question slightly after realising I have probably confused matters by specifying a type parameter in the Factory creation method. What I have is two types of API calls that I need to make to a 3rd party API. The first retrieves a record from the API using an Id that is an int. The second also retrieves a record from the API but the Id is a string (guid). I have a class for each record type (ClientEntity and InvoiceEntity) that both implement a Generic Interface where I pass in the Id type
This is the Interface in which I declare a Method with an id Parameter
public interface IGeneric<TId>
{
void ProcessEntity(TId id);
}
I implement the interface in a couple of classes, one sets the id to be an int, the other a string.
public class ClientEntity: IGeneric<int> // Record with Id that is an int
{
public void ProcessEntity(int id)
{
Console.WriteLine(id);
// call 3rd party API with int Id
}
}
public class InvoiceEntity: IGeneric<string> // Record with Id that is a string (guid)
{
public void ProcessEntity(string id)
{
Console.WriteLine(id);
// call 3rd party API with string Id
}
}
What I would like to know is how do I use this within a factory pattern?
public static class GenericFactory
{
public static IGeneric<WhatGoesHere> CreateGeneric(string recordType)
{
if (recordType == "Client")
{
return new ClientEntity();
}
if (type == "Invoice")
{
return new InvoiceEntity();
}
return null;
}
}
The objective is to use the factory to instantiate the correct class so that I can call the ProcessEntity method
EDIT
I don't want to have to pass in the Generic type to the factory method because the class that is created by the factory should handle that. When I create the object, I don't know what Id type is required, I want the factory to handle that
e.g.
var myGeneric = GenericFactory.CreateGeneric("Client");
myGeneric.ProcessEntity("guid")
or
var myGeneric = GenericFactory.CreateGeneric("Invoice");
myGeneric.ProcessEntity(1234)
I hope that makes sense
You should be able to do something like this:
public static class GenericFactory
{
public static IGeneric<T> CreateGeneric<T>()
{
if (typeof(T) == typeof(string))
{
return (IGeneric<T>) new GenericString();
}
if (typeof(T) == typeof(int))
{
return (IGeneric<T>) new GenericInt();
}
throw new InvalidOperationException();
}
}
You would use it like this:
var a = GenericFactory.CreateGeneric<string>();
var b = GenericFactory.CreateGeneric<int>();
Note that this uses a strongly-typed call rather than passing in the type name as a string (which may or may not be what you actually want).
If instead you want to pass a string for the type name, you will have to return an object because there is no way to return the actual type:
public static object CreateGeneric(string type)
{
switch (type)
{
case "string": return new GenericString();
case "int": return new GenericInt();
default: throw new InvalidOperationException("Invalid type specified.");
}
}
Obviously if you have an object you would normally have to cast it to the right type in order to use it (which requires that you know the actual type).
Alternatively, you could use reflection to determine what methods it contains, and call them that way. But then you'd still need to know the type in order to pass a parameter of the right type.
I think that what you are attempting to do here is not the right approach, which you will discover once you start trying to use it.
Hacky solution: Use dynamic
Nevertheless, there is one way you can get something close to what you want: Use dynamic as follows (assuming that you are using the object CreateGeneric(string type) factory method from above):
dynamic a = GenericFactory.CreateGeneric("string");
dynamic b = GenericFactory.CreateGeneric("int");
a.ProcessEntity("A string");
b.ProcessEntity(12345);
Be aware that dynamic uses reflection and code generation behind the scenes, which can make the initial calls relatively slow.
Also be aware that if you pass the wrong type to a method accessed via dynamic, you'll get a nasty runtime exception:
dynamic a = GenericFactory.CreateGeneric("string");
a.ProcessEntity(12345); // Wrong parameter type!
If you run that code, you get this kind of runtime exception:
Unhandled Exception: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: The best overloaded method match for 'ConsoleApplication1.GenericString.ProcessEntity(string)' has some invalid arguments
at CallSite.Target(Closure , CallSite , Object , Int32 )
at System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid2[T0,T1](CallSite site, T0 arg0, T1 arg1)
at ConsoleApplication1.Program.Main() in D:\Test\CS6\ConsoleApplication1\Program.cs:line 71
Usually for that Factory using some DI container (DI can be useful, for example, when GenericInt or GenericString has dependencies), but to demonstrate just Idea how you can resolve this:
void Main()
{
GenericFactory.CreateGeneric<int>();
GenericFactory.CreateGeneric<string>();
}
public static class GenericFactory
{
private static Dictionary<Type, Type> registeredTypes = new Dictionary<System.Type, System.Type>();
static GenericFactory()
{
registeredTypes.Add(typeof(int), typeof(GenericInt));
registeredTypes.Add(typeof(string), typeof(GenericString));
}
public static IGeneric<T> CreateGeneric<T>()
{
var t = typeof(T);
if (registeredTypes.ContainsKey(t) == false) throw new NotSupportedException();
var typeToCreate = registeredTypes[t];
return Activator.CreateInstance(typeToCreate, true) as IGeneric<T>;
}
}
public interface IGeneric<TId>
{
TId Id { get; set; }
void ProcessEntity(TId id);
}
public class GenericInt : IGeneric<int>
{
public int Id { get; set; }
public void ProcessEntity(int id)
{
Console.WriteLine(id);
}
}
public class GenericString : IGeneric<string>
{
public string Id { get; set; }
public void ProcessEntity(string id)
{
Console.WriteLine(id);
}
}
The answer marked correct is fine if you want to use Static class but but what if you
want to return an DI injected type instead of newing an object? I suggest the
following!
public interface IGenericFactory
{
IGeneric<T> GetGeneric<T>() where T : class;
}
public class GenericFactory: IGenericFactory
{
private readonly IGeneric<int> intGeneric;
private readonly IGeneric<string> stringGeneric;
public GenericFactory(IGeneric<int> intG, IGeneric<string> stringG)
{
intGeneric = intG;
stringG = stringG;
}
public IGeneric<T> GetGeneric<T>() where T : class
{
if (typeof(T) == typeof(IGeneric<int>))
return (IGeneric<T>)Convert.ChangeType(intGeneric, typeof(IGeneric<T>));
if (typeof(T) == typeof(IGeneric<string>))
return (IGeneric<T>)Convert.ChangeType(stringGeneric,typeof(IGeneric<T>));
else
throw new NotSupportedException();
}
}
Please note i simply injected the two expected return types for clarity in the constructor. I could have implemented the factory as a Dictionary and injected the return objects into this Dictionary. Hope it helps.
I'm thinking you don't want to have to enter the type parameter similar to the LINQ methods. However the magic behind that happens because the type parameter is used in the normal parameter definitions. For example in the ToList<string>() method you can see that TSource is used between the parenthesis.
public static List<TSource> ToList<TSource>(this IEnumerable<TSource> source);
That's how the compiler knows that you want a List<string> if you call ToList() instead of ToList<string>() when called from an IEnumerable<string>
However, I don't think you need a generic type parameter in your factory method at all. All you have to do is create a non-generic version of your TGeneric<TId>
public interface IGeneric { }
public interface IGeneric<TId> : IGeneric
{
void ProcessEntity(TId id);
}
And remove the <WhatGoesHere> from the CreateGeneric method:
public static IGeneric CreateGeneric(string recordType)
{
if (recordType == "Client")
{
return new ClientEntity();
}
if (recordType == "Invoice")
{
return new InvoiceEntity();
}
return null;
}
If the function does not know the type, make it generic.
If the children are generics of different types (<int>, <string>), return object and cast inside the same factory class (Factory<T>), It is safe by typeof.
Personally, I prefer to specify the type with generics, without using an additional parameter, eg a string.
public class Program
{
public static void Main(string[] args)
{
List<Number> something = new();
Do(something);
}
public static void Do<T>(List<T> list)
{
list.Add(Factory<T>.Create());
}
}
public abstract class Factory<T>
{
private static Object ConcreteF()
{
if (typeof(T) == typeof(Number))
return new ChildGenericNumber();
throw new Exception("");
}
public static T Create()
{
return (Factory<T>)ConcreteF()).Build();
}
protected abstract T Build();
}
I have about 1000 classes in which i need to count the number of properties of. I have the following code:
public static int NumberOfProperties()
{
Type type = typeof(C507);
return type.GetProperties().Count();
}
I could copy and paste this in to each class changing the typeof parameter but this seems a bit tedious.
Is there anyway to make an extensions method to do this by just doing var nop = C507.NumberOfProperties();?
Just to add to the answers suggesting an extension for object for completeness: you can also consider implementing an extension only for Type:
public static int GetPropertyCount(this Type t)
{
return t.GetProperties().Length;
}
and use it like this:
typeof(C507).GetPropertyCount();
The advantage is that you can get the number of properties directly from the type and do not have to create an instance first.
So you can write an extension method that uses object or one that uses type.
public static class ObjectExtensions
{
public static int GetNumberOfProperties(this object value)
{
return value.GetType().GetProperties().Count();
}
public static int GetNumberOfProperties(this Type value)
{
return value.GetProperties().Count();
}
}
Usage:
new C507().GetNumberOfProperties();
typeof(C507).GetNumberOfProperties();
However, you explicitly state two things:
I could copy and paste this in to each class changing the typeof
I have about 1000 classes
You'll likely not want to instantiate a 1000 classes or copy and paste typeof() 1000 times
In this case, you will want to read them all from the Assembly.
So something like:
typeof(SomeClass).Assembly.GetTypes().Select(x => new
{
x.Name,
PropertyCount = x.GetType().GetProperties().Count()
});
Where SomeClass is a class (doesn't matter which) where all the classes reside.
I just simply select them out into an anonymous object which contains the Types name and property count.
This:
typeof(SomeClass).Assembly
Is just a convience way to get the assembly. There are other ways.
Assembly.GetAssembly(typeof(Program)).GetTypes()
Assembly.GetCallingAssembly().GetTypes()
Assembly.Load("Some Assemble Ref").GetTypes()
You can do allsorts with the types that you find. If you select out the Type itself, you can instantiate it later using Activator.CreateInstance (if it has parameterless constuctor). You can also auto fill the properties with reflection as well.
It is impossible to have a static extension method as you imagine it. That being said, it would be possible to create a generic method in a helper class as follows.
public static int NumberOfProperties<T>()
{
Type type = typeof(T);
return type.GetProperties().Count();
}
Given a type SomeType it could be called as int n = NumberOfProperties<SomeType>().
You could make an extension method on object like this:
public static int PropertyCount(this object thing)
{
return thing.GetType().GetProperties().Count();
}
And use it on any object you like:
var x = "some string";
var numProps = x.PropertyCount();
If you want to have an extension method on object:
public static ObjectExtensions
{
public static int NumberOfProperties(this object value)
{
if (null == value)
throw new ArgumentNullException("value"); // or return 0
// Length: no need in Linq here
return value.GetType().GetProperties().Length;
}
}
...
C507 myObj = new C507();
// How many properties does myObj instance have?
int propCount = myObj.NumberOfProperties();
If you want to have an extesnion method on Type:
public static TypeExtensions
{
public static int NumberOfProperties(this Type value)
{
if (null == value)
throw new ArgumentNullException("value"); // or return 0
// Length: no need in Linq here
return value.GetProperties().Length;
}
}
...
// How many properties does C507 type have?
int propCount = typeof(C507).NumberOfProperties();
There are a couple of ways to do this that are variations of the same thing.
You can pass the Type as an argument to a method:
public static class Helper {
public static int NumberOfProperties(Type type)
{
return type.GetProperties().Count();
}
}
Which you would call like this:
// Imagine you have a class called MyClass
var result = Helper.NumberOfProperties(typeof(MyClass));
You use use the generic system in C# to make the syntax a little cleaner. That would look like this:
public static class Helper {
// Notice the argument was removed and
// the use of the "generic" syntax <T>
public static int NumberOfProperties<T>()
{
var type = typeof(T);
return type.GetProperties().Count();
}
}
And you would call it like this:
var result = Helper.NumberOfProperties<MyClass>();
You could also use "Extensions" which allow you to call it as if it was a method that belonged to your classes.
public static class Helper {
// notice the `this` keyword before the parameter
// this is what tells C# that this is an extension method
public static int NumberOfProperties<T>(this T #this)
{
var type = typeof(T);
return type.GetProperties().Count();
}
}
This will allow you to call the method like this:
var instance = new MyClass();
var result = instance.NumberOfProperties();
In this example I used the generic syntax so that it applies to any type of object. If you wanted to limit it to only objects that inherit from a specific interface or base class you would just change it from using the generic syntax to using the base class/interface. Like this:
public static class Helper {
// notice the type got changed from a generic <T>
// to specifying the exact class you want to "extend"
public static int NumberOfProperties(this MyBaseClass #this)
{
var type = typeof(T);
return type.GetProperties().Count();
}
}
As #rené-vogt mentioned you can also create the extension method so that it extends the type Type instead. See his answer in this thread: https://stackoverflow.com/a/38455233/984780
You can make a generic extension method which can apply to all types:
public static int PropertyCount<T>(this T obj)
{
return typeof(T).GetProperties().Length;
}
This will apply to all types including value types (I.E. structs) which applying to object will not. Thanks to piedar for pointing out my mistake here, applying to object does still add this extension method to value types.
If your classed can implement an interface, then you can extend that interface.
public interface IExtensible {
}
class C507 : IExtensible {
}
public static int NumberOfProperties(this IExtensible extensible)
{
Type type = extensible.GetType();
return type.GetProperties().Count();
}
That being said, having hundreds of (generated?) classes looks like a bad solution to begin with.
I have a method which is something like below and i want to set the value of it with input string.
How would i go about it? Any advice will be greatly appreciated
private static void QueueCheckNAdd<T>(ref T param, string input)
{
param.DoSomethingLikeSetValue(input);
}
for your reference, the generic type is something like int or double
param = (T)(object)Convert.ChangeType(input, typeof(T));
The casts are necessary to convince the compiler that the result is really of type T.
You want param to be generic (i.e., any type), and you expect to be able to call some method on it, correct? Well, you can see the problem there: if param can be any type, there's no way to guarantee that it will have the method DoSomethingLikeSetValue (or whatever). I'm sure you could get fancy with introspection or runtime type coercion, but I think the "clean" way to do what you're looking for is to constrain the type of T to some interface that has the required method (DoSomethingLikeSetValue). Like this:
private static void QueueCheckNAdd<T>(ref T param, string input) where T : IHasSomething {
param.DoSomethingLikeSetValue(input);
}
public interface IHasSomething {
void DoSomethingLikeSetValue(string s);
}
Then you can invoke QueueCheckNAdd generically only if the generic type supports the IHasSomething interface. So you could use it like this:
public class Foo : IHasSomething {
public void DoSomethingLikeSetValue(string s) {
Console.WriteLine(s);
}
}
var f = new Foo();
QueueCheckNAdd<Foo>(f, "hello");
Good practice would be to use interface like described before,
But if you want some fun, you could aslo use the object as a dynamic object, like below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class SMTHG
{
public void DoSomethingLikeSetValue(string input)
{
Console.WriteLine("HEYYYYY!!! DYNAMIC OBJECTS FTW!...\n" + input);
}
}
class Program
{
private static void QueueCheckNAdd<T>(ref T param, string input)
{
dynamic dynamicObject = (dynamic)param;
dynamicObject.DoSomethingLikeSetValue(input);
}
static void Main(string[] args)
{
SMTHG smthg = new SMTHG();
QueueCheckNAdd(ref smthg, "yoyuyoyo");
}
}
}
I am trying to hand-roll my own IoC tool.
This is a part of IoC code:
public static object Resolve(Type contract)
{
Type Implementation = typeSettings[contract];
ConstructorInfo constructor = Implementation.GetConstructors()[0];
ParameterInfo[] constructorParam = constructor.GetParameters();
if (constructorParam.Length == 0)
Activator.CreateInstance(Implementation);
List<object> paramList = new List<object>(constructorParam.Length);
foreach(ParameterInfo param in constructorParam)
paramList.Add(Resolve(param.ParameterType));
return constructor.Invoke(paramList.ToArray());
}
I want to return an object of the generic type T. I am not able to do that.
I am not able to typecast it either. I am using only one interface with two dependencies.
(IPredictingFuture, EartAndSkyPrediction, BadConnections)
I am trying to typecast it to the Interface type. (In order to access the methods in my client code.) But that is not working out either.
What am I missing?
In your method, contract is only known at runtime, so it cannot be used at compile time. Depending on your callers, you may be able to change it to a generic type parameter, in which case you can do:
public static object Resolve(Type contract)
{
Type Implementation = typeSettings[contract];
ConstructorInfo constructor = Implementation.GetConstructors()[0];
ParameterInfo[] constructorParam = constructor.GetParameters();
if (constructorParam.Length == 0)
Activator.CreateInstance(Implementation);
List<object> paramList = new List<object>(constructorParam.Length);
foreach(ParameterInfo param in constructorParam)
paramList.Add(Resolve(param.ParameterType));
return constructor.Invoke(paramList.ToArray());
}
public static T Resolve<T>()
{
return (T)Resolve(typeof(T));
}
Overloaded because as you mention, Resolve(Type) calls itself recursively, and the generic version cannot call itself like that.
Adjusting the namespace for this venue, I've used this for years...
using System;
using System.Collections.Generic;
using DataAccess.Core.DataInterfaces;
using DataAccess.Core.Utils;
namespace StackOverflowExample
{
public class SimpleIoC<T>
{
public T getInstance()
{
return getInstance(null);
}
public T getInstance(object[] initializationParameters)
{
Type type = Activator.CreateInstance(typeof(T), initializationParameters).GetType();
// Any special initialization for an object should be placed in a case statement
// using that object's type name
switch (type.ToString())
{
// Example
//case "DataAccess.Data.ApplicantDao":
// // - Do pre-instanciation initialization stuff here -
// return (T)Activator.CreateInstance(typeof(T), initializationParameters);
default:
return (T)Activator.CreateInstance(typeof(T), initializationParameters);
}
}
}
}
Not sure if this one will help you, but I use this as part of a Business Rule Evaluation Engine...
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
namespace StackOverflowExample
{
public static class DynamicObjectFactory
{
private static readonly object _lock = new object();
public static object getInstance(string assemblyName, string className)
{
Monitor.Enter(_lock);
try
{
System.Reflection.Assembly asm = System.Reflection.Assembly.Load(assemblyName);
return asm.CreateInstance(className, false, System.Reflection.BindingFlags.CreateInstance, null, null, null, null);
}
finally
{
Monitor.Exit(_lock);
}
}
public static object getInstance(string assemblyName, string className, object[] constructorParameters)
{
Monitor.Enter(_lock);
try
{
System.Reflection.Assembly asm = System.Reflection.Assembly.Load(assemblyName);
return asm.CreateInstance(className, false, System.Reflection.BindingFlags.CreateInstance, null, constructorParameters, null, null);
}
finally
{
Monitor.Exit(_lock);
}
}
}
}
Thanks guys, for the response.
I added this overridden Resolve method
public static T Resolve<T>() { return (T)Resolve(typeof(T)); }
Now, I get the type properly. This is the client code:
IPredictingFuture predictions;
predictions = IoC.Resolve<IPredictingFuture>();
This way, the intellisense after predictions works just fine.
If any of the readers landed up at this question because they are trying to cook up an IoC container, I would point them to these great links:
33 liner IoC by Ken
15 liner IoC by Ayende
Followup post by Ayende on why you should not be coding your own IoC
Good link about IoC containers
Another SO question which talks about IoC