簡體   English   中英

如何在.net Core 2.2控制台應用程序中實現依賴項注入

[英]How to implement dependency injection in .net core 2.2 console application

我正在使用.net core 2.2創建一個小型控制台應用程序,並且試圖通過我的應用程序實現依賴項注入。 我遇到了一些未處理的異常。

人.cs

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

IPerson存儲庫

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"
                });
        }
    }
}


我收到此Exception 有人可以告訴我我在哪里犯錯嗎? 我也想知道何時使用DI在控制台應用程序(不運行24 * 7)中制作.exe是安全的?
任何幫助將非常感激。 謝謝

您的人員存儲庫采用了IPersonRepository,Dependency Injector試圖創建一個需要在其中注入自身的類。 您可能想改用DbContext。 此代碼假定您已經創建了一個名為ApplicationContext的DbContext。

private readonly ApplicationContext _context;

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

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

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

這是你的問題。 您需要從構造函數中刪除IPersonRepository參數,因為它試圖在自身內部創建其自身的實例。 因此,您的循環參考問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM