c# - 如何解决.net core中Web API构造函数的依赖关系

标签 c# dependency-injection asp.net-core asp.net-core-mvc asp.net-core-webapi

我是 .net core 和依赖注入(inject)概念的新手。我想在Web API构造函数中注入(inject)服务接口(interface),服务接口(interface)和实现位于不同的项目中。请找到我的应用程序的以下各层,

Application Layers

在startup.cs中,我已经添加了以下行,

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc();

    services.AddSingleton<IEntriesService, EntriesService>();
}

我的 Controller ,

public class EntriesController : Controller
{
    IEntriesService entryService;
    public EntriesController(IEntriesService _entryService)
    {
        entryService = _entryService;
    }

    // GET: api/values
    [HttpGet]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }
}

问题是,当我执行 API 应用程序时,它没有命中我的构造函数并显示如下空白页面,

Error page

无需添加构造函数,应用程序就可以正常工作。

我的IEentriesService,

public interface IEntriesService
{
    RepeatEntries Get(int Id);
}

我的参赛作品服务,

public class EntriesService : IEntriesService
{
    IUnitOfWork _unitOfWork;
    public EntriesService(IUnitOfWork unitOfWork)
    {
        _unitOfWork = unitOfWork;
    }

    public bool Add(RepeatEntries entity)
    {
        _unitOfWork.EntryRepository.Add(entity);
        return true;
    }
}

我的 IUnitOfWork,

public interface IUnitOfWork : IDisposable
{
    IEntriesRepository EntryRepository { get; }
    void Complete();
}

我的工作单元,

public class UnitOfWork : IUnitOfWork
{
    private readonly IEntriesRepository _entryRepository;
    public UnitOfWork(IEntriesRepository entryRepository)
    {
        _entryRepository = entryRepository;
    }

    public IEntriesRepository EntryRepository
    {
        get
        {
            return _entryRepository;
        }
    }

    void IUnitOfWork.Complete()
    {
        throw new NotImplementedException();
    }

    #region IDisposable Support
    private bool disposedValue = false; // To detect redundant calls



    protected virtual void Dispose(bool disposing)
    {
        if (!disposedValue)
        {
            if (disposing)
            {
                // TODO: dispose managed state (managed objects).
            }

            // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
            // TODO: set large fields to null.

            disposedValue = true;
        }
    }

    // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
    // ~UnitOfWork() {
    //   // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
    //   Dispose(false);
    // }

    // This code added to correctly implement the disposable pattern.
    void IDisposable.Dispose()
    {
        // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
        Dispose(true);
        // TODO: uncomment the following line if the finalizer is overridden above.
        // GC.SuppressFinalize(this);
    }
    #endregion
}

我还需要添加什么才能使其正常工作?是否有可能或者我需要改变我的方法?

最佳答案

您必须向组合根注册所有依赖项,确保以正确的生命周期注册它们,即:(ScopedTransientSingleton)以避免将来出现问题。

public void ConfigureServices(IServiceCollection services) {
    // Add framework services.
    services.AddMvc();

    services.AddSingleton<IEntriesService, EntriesService>();
    services.AddTransient<IUnitOfWork, UnitOfWork>();
    services.AddTransient<IEntriesRepository, EntriesRepository>();
    services.AddSingleton<IConnectionFactory, ConnectionFactory>();

    //...add other dependencies. 
}

花一些时间查看文档:

Introduction to Dependency Injection in ASP.NET Core

关于c# - 如何解决.net core中Web API构造函数的依赖关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43718258/

相关文章:

javascript - InversifyJS @multiInject 不工作,抛出错误 "Ambiguous match found for serviceIdentifier"

javascript - 这两种声明 AngularJS Controller 的方式有什么区别?

c# - 如何在 cshtml View 中使用 Asp .NET Core MVC 中的变量?

asp.net - asp.net core 中的单元测试 UserManager<IdentityUser>

c# - 使用 SystemEvents.UserPreferenceChanged 和多个 UI 线程时 UI 卡住

c# - 所有 JPEG 文件都是 JFIF 吗?

c# - 减少不断增加的构造函数服务参数

c# - 从 WebAPI Controller 获取声明 - JWT token ,

c# - WinForms 列表框中的项目数限制

c# - 如何获取放置到控制台应用程序窗口中的项目的文件路径?