Вот что я пробовал:
Код: Выделить всё
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()
{
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 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;
}
Необработанное исключение. System.InvalidOperationException: последовательность не содержит элементов
в System.Linq.ThrowHelper.ThrowNoElementsException()
в System.Linq.Enumerable.First[TSource](источник IEnumerable`1)
В отладчике я пытался просмотреть свойства типа, но для первичного конструктора ничего не нашел. Есть ли способ найти основной конструктор, чтобы мой код работал без объявления обычного конструктора.
Подробнее здесь: https://stackoverflow.com/questions/789 ... in-c-sharp
Мобильная версия