I’m working on creating my own dependency injection framework in C# as a learning exercise. However, I’m encountering an issue when trying to get the primary constructor of a class from its type.
Here is what I’ve tried:
public class HelloService(MessageService service)
{
public void Print()
{
Console.WriteLine("Hello " + service.Message());
}
}
public class Dependency(Type type, DependencyLifetime lifetime)
{
public DependencyLifetime Lifetime { get; set; } = lifetime;
public Type Type { get; set; } = type;
public object Instance { get; set; }
public bool Initialized { get; set; } = false;
}
public T GetService<T>()
{
return (T) GetService(typeof(T));
}
public object GetService(Type type)
{
var dependency = _container.GetDependency(type);
var constructors = type.GetConstructors();
var constructor = constructors.First();
var parameters = constructor.GetParameters();
if (parameters.Length > 0)
{
var parameterImplementations = new object[parameters.Length];
for (int i = 0; i < parameters.Length; i++)
{
parameterImplementations[i] = GetService(parameters[i].ParameterType);
}
return CreateImplementation(dependency, () => constructor.Invoke(parameterImplementations));
}
return CreateImplementation(dependency, () => Activator.CreateInstance(type));
}
public object CreateImplementation(Dependency dependency, Func <Object> factory)
{
if (dependency.Initialized)
{
return dependency.Instance;
}
var implementation = factory();
if (dependency.Lifetime == DependencyLifetime.Transient)
{
return implementation;
}
dependency.Initialized = true;
dependency.Instance = implementation;
return implementation;
}
Once I run this code, I get the following error:
Unhandled exception. System.InvalidOperationException: Sequence contains no elements
at System.Linq.ThrowHelper.ThrowNoElementsException()
at System.Linq.Enumerable.First[TSource](IEnumerable`1 source)
In the debugger I tried looking at the properties of type, but I couldn’t find anything for the primary constructor. Is there a way to find primary constructor, so my code works without declaring the normal constructor.
Vasilije Bozaric is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
3