我是.net核心和依赖注入概念的新手。我想在Web API构造函数中注入服务接口,Service接口和实现在不同的项目中。请查看我的应用程序的以下层,
在startup.cs中,我已添加以下行
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.AddSingleton<IEntriesService, EntriesService>();
}
我的控制器,
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应用程序时,它没有点击我的构造函数并显示空白页面,如下所示,
不添加构造函数,Application正常工作。
我的IEntriesService,
public interface IEntriesService
{
RepeatEntries Get(int Id);
}
我的EntriesService,
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
}
我需要添加什么才能使其正常工作?是否有可能或我需要改变我的方法?
答案 0 :(得分:3)
您必须使用组合根注册所有依赖项,确保使用正确的生命周期注册它们,即:(Scoped
,Transient
,Singleton
)以避免将来出现问题。
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.
}
花一些时间查看文档: