【发布时间】:2016-10-25 04:08:07
【问题描述】:
我正在尝试使用存储库模式创建 MVC API。以下是我的代码
IInsurerDAL.cs
namespace InformationServices.DAL
{
public interface IInsurerDAL
{
Task<DataTable> GetInsurer(string cover,string version);
}
}
InsurerDAL.cs
namespace InformationServices.DAL
{
public class InsurerDAL : IInsurerDAL
{
int commandTimeout;
public InsurerDAL()
{
Int32.TryParse(ConfigurationManager.AppSettings["CommandTimeout"], out commandTimeout);
if (commandTimeout <= 0)
{
commandTimeout = 30;
}
}
public async Task<DataTable> GetInsurer(string cover, string version)
{
//some code
}
}
}
IInsurerRepository.cs
namespace InformationServices.Repository
{
public interface IInsurerRepository
{
ConsumerDetails ConsumerDetails { get; set; }
Task<ResponseModel<Insurer>> GetInsurer(string cover, string version);
}
}
InsurerRepository.cs
namespace InformationServices.Repository
{
public class InsurerRepository : IInsurerRepository, IDisposable
{
InsurerDAL oInsurerDAL;
ConsumerDetails oConsumerDetails { get; set; }
public ConsumerDetails ConsumerDetails
{
get
{
return oConsumerDetails;
}
set
{
oConsumerDetails = value;
}
}
public InsurerRepository()
{
var container = new UnityContainer();
oInsurerDAL = container.Resolve<InsurerDAL>();
MapperRegistry.Mappers.Add(new DataReaderMapper());
//To load the DataReaderMapper before we actually use it.
var type = typeof(DataReaderMapper);
}
public async Task<ResponseModel<Insurer>> GetInsurer(string cover, string version)
{
}
//Implementation of IDisposable interfase.
protected void Dispose(bool disposing)
{
if (disposing)
{
if (oInsurerDAL != null)
{
oInsurerDAL = null;
}
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}
InsurerController.cs
namespace InformationServices.API.Controllers
{
[RoutePrefix("V1")]
[ControllerExceptionFilter]
public class InsurerController : ApiController
{
private IInsurerRepository InsurerRepository;
private static ILog logger = log4net.LogManager.GetLogger(typeof(InsurerController));
public InsurerController(IInsurerRepository repository)
{
InsurerRepository = repository;
InsurerRepository.ConsumerDetails = CommonFunctions.FetchConsumerDataFromHeader();
}
[HttpGet]
[HttpOptions]
public async Task<IHttpActionResult> GetInsurer(string cover, string version, string srcKey)
{
//code here
}
}
}
我也在使用下面的代码将它注册到一个容器中
var container = new UnityContainer();
container.RegisterType<IInsurerDAL, InsurerDAL>(new HierarchicalLifetimeManager());
GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
当我尝试使用此 Web API 时,我仍然遇到以下问题:
依赖关系解析失败,类型= \"InformationServices.API.Controllers.InsurerController\",名称 = \"(none)\"。\r\n出现异常 while: 解析时。\r\n异常 是: InvalidOperationException - 当前类型, InformationServices.Repository.IInsurerRepository,是一个接口和 无法构建。您是否缺少类型映射?
【问题讨论】:
标签: asp.net asp.net-mvc asp.net-mvc-3 asp.net-mvc-4 asp.net-web-api