У меня есть ASP.NET MVC 4 проекта, в котором пытаются реализовать следующие технологии & модели:DI + Общий репо + общий контекст + единица работы не работает, почему?
- Dependency Injection на основе Unity.MVC4
- Единица работы с родовым хранилище & контекста
- код первого
Но это возвращает ошибку:
The current type, JobParsing.Models.IContext`1[JobParsing.Models.Entities.Product], is an interface and cannot be constructed. Are you missing a type mapping?
Код следующий (извините за большой объем кода, просто за конкретное изображение). Кто-нибудь знает, где моя ошибка?
Модель:
public class Product {
public int Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public decimal Price { get; set; }
}
Сущности:
public class DbEntities : DbContext {
public DbEntities() : base("DefaultConnection") {
}
public DbEntities(string connString)
{
this.Database.Connection.ConnectionString = ConfigurationManager.ConnectionStrings[connString].ConnectionString;
}
public DbSet<Product> Products { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
Контекст:
public interface IContext<T> : IDisposable where T : class {
DbContext DbContext { get; }
IDbSet<T> DbSet { get; }
DbEntities EntitiesForSp { get; }
}
public class GenContext<T> : IContext<T> where T : class {
public GenContext() {
DbContext = new DbEntities();
DbSet = DbContext.Set<T>();
EntitiesForSp = new DbEntities();
}
public GenContext(DbContext context) {
DbContext = context;
DbSet = DbContext.Set<T>();
}
#region IContext<T> Members
public DbContext DbContext {
get;
private set;
}
public DbEntities EntitiesForSp {
get;
private set;
}
public IDbSet<T> DbSet {
get;
private set;
}
#endregion IContext<T> Members
#region IDisposable Members
public void Dispose() {
if (this.DbContext != null) this.DbContext.Dispose();
}
#endregion IDisposable Members
}
Repository:
public interface IGenericRepository<TEntity> where TEntity : class {
IQueryable<TEntity> GetAll();
DbContext Context { get; }
int Save();
}
public class GenericRepository<TEntity> : IGenericRepository<TEntity> where TEntity : class {
private IContext<TEntity> _context;
public DbContext Context {
get { return _context.DbContext; }
}
public GenericRepository() {
_context = new GenContext<TEntity>();
}
public GenericRepository(IContext<TEntity> context) {
_context = context;
}
public IQueryable<TEntity> GetAll() {
IQueryable<TEntity> query = this._context.DbContext.Set<TEntity>();
return query;
}
public int Save() {
return _context.DbContext.SaveChanges();
}
public void Dispose(bool disposing) {
if (disposing) {
if (_context != null) {
_context.Dispose();
_context = null;
}
}
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
}
Единица работы:
public interface IUnitOfWork {
GenericRepository<Product> ProductRepository { get; }
}
public class UnitOfWork : IUnitOfWork {
protected string ConnectionString;
private GenericRepository<Product> productRepository;
public UnitOfWork(string connectionString) {
this.ConnectionString = connectionString;
}
public UnitOfWork(GenericRepository<Product> productRepository) {
this.productRepository = productRepository;
}
public GenericRepository<Product> ProductRepository {
get {
if (this.productRepository == null) {
this.productRepository = new GenericRepository<Product>();
}
return productRepository;
}
}
}
Услуги:
public interface IService {
IEnumerable<Product> GetProducts();
}
public class Service : IService {
private IUnitOfWork unitOfWork;
public Service(IUnitOfWork unitOfWork, IGenericRepository<Product> productRepository) {
this.unitOfWork = unitOfWork;
//this.productRepository = productRepository;
}
public IEnumerable<Product> GetProducts() {
var movies = unitOfWork.ProductRepository.GetAll().ToList();
return movies;
}
}
Bootstrapper:
public static class Bootstrapper {
public static IUnityContainer Initialise(string connectionString) {
var container = BuildUnityContainer(connectionString);
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
return container;
}
private static IUnityContainer BuildUnityContainer(string connectionString) {
var container = new UnityContainer();
// Register everything with Unity. A single line of code registers GenericRepository for all Entity types.
// Specific repositories, if defined, will also get registered here.
// Unity.MVC3 takes care of the MVC controllers so they are not registered here.
container.RegisterType<IUnitOfWork, UnitOfWork>(new HierarchicalLifetimeManager(),
new InjectionConstructor(connectionString));
container.RegisterType(typeof(IGenericRepository<>), typeof(GenericRepository<>));
container.RegisterType<IService, Service>();
return container;
}
public static void RegisterTypes(IUnityContainer container) {
}
}
Контроллер:
public class HomeController : Controller {
private IService service;
public HomeController(IService service)
{
this.service = service;
}
public ActionResult Products()
{
var genres = this.service.GetProducts().ToList();
return View(genres);
}
}
Какая линия выдает ошибку? – Andrei
@Andrei Возврат к просмотру. Последняя строка, которая работает правильно, находится в файле Global.asax.cs Bootstrapper.Initialise («DefaultConnection»); Database.SetInitializer (новый Initializer()); но после последней строки я увидел ошибку. –
BorHunter