Как реализовать внедрение зависимостей в консольном приложении .net core 2.2 - PullRequest
0 голосов
/ 25 января 2019

Я создаю небольшое консольное приложение, использующее ядро ​​.net 2.2, и пытаюсь внедрить внедрение зависимостей в мое приложение.Я получаю некоторые необработанные исключения.

Person.cs

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int? Age { get; set; }
    public string Gender { get; set; }
}

IPersonRepository

public interface IPersonRepository
{
     bool AddPerson(Person entity);
     IEnumerable<Person> GetAllPersons();
}

PersonRepository.cs

 public class PersonRepository:IPersonRepository
 {
        private readonly IPersonRepository _personRepository;

        public PersonRepository(IPersonRepository personRepository)
        {
            _personRepository = personRepository;
        }

        public bool AddPerson(Person entity)
        {
            _personRepository.AddPerson(entity);
            return true;
        }

        public IEnumerable<Person> GetAllPersons()
        {
            throw new System.NotImplementedException();
        }
  }

Program.cs

using Microsoft.Extensions.DependencyInjection;

namespace ConsoleAppWithDI
{
    internal static class Program
    {
        private static void Main(string[] args)
        {
            var serviceProvider = new ServiceCollection()
                .AddTransient<IPersonRepository, PersonRepository>()
                .BuildServiceProvider();

            var personRepositoryObj = serviceProvider
                .GetService<IPersonRepository>();

            personRepositoryObj
                .AddPerson(new Person
                {
                    Id = 1,
                    Name = "Tom",
                    Age = 24,
                    Gender = "Male"
                });
        }
    }
}


Я получаю это Исключение .Кто-нибудь может сказать мне, где я делаю ошибку?Также я хотел бы знать, безопасно ли делать .exe в консольном приложении (которое не работает 24 * 7) с использованием DI?
Любая помощь будет высоко ценится.Спасибо

Ответы [ 2 ]

0 голосов
/ 06 февраля 2019
public PersonRepository(IPersonRepository personRepository)
{
    _personRepository = personRepository;
}

Это ваша проблема. Вам необходимо удалить параметр IPersonRepository из конструктора, поскольку он пытается создать собственный экземпляр внутри себя. Следовательно, ваша круговая ссылка выпуска

0 голосов
/ 25 января 2019

Ваш личный репозиторий берет IPersonRepository, Dependency Injector пытается создать класс, в который он должен внедрить себя. Вы, вероятно, хотите взять вместо DbContext. Этот код предполагает, что вы создали DbContext с именем ApplicationContext

private readonly ApplicationContext _context;

public PersonRepository(ApplicationContext context)
{
    _context = context;
}

public bool AddPerson(Person entity)
{
    _context.Persons.Add(entity);
    _context.SaveChanges();

    return true;
}
...