Soy nuevo en Ninject, así que estoy seguro de que es algo que estoy haciendo mal, no estoy seguro de qué. Estoy usando Ninject y Ninject.MVC3 en mi aplicación web MVC3. Aquí hay un ejemplo de lo que intento hacer.Ninject no inyectar y lanzar excepciones de referencia nulas
estoy usando el patrón Repositorio:
public interface IRepository<T>
{
T Get(object id);
IList<T> GetAll();
void Add(T value);
void Update(T value);
void Delete(T value);
}
Para un tipo concreto:
public Customer
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public Customer()
{
}
}
Ahora tengo 2 repositorios separados, una versión en caché que necesita la inyección en el repositorio de datos:
public CachedCustomerRepository : IRepository<Customer>
{
private IRepository<Customer> _repository;
public Customer Get(object id)
{
Customer cust = new Customer();
IList<Customer> custs = GetAll();
if (custs != null && custs.Count > 0)
cust = custs.FirstOrDefault(c => c.Id == int.Parse(id.ToString()));
return cust;
}
public IList<Customer> GetAll()
{
IList<Customer> custs = HttpRuntime.Cache["Customers"] as IList<Customer>;
if (custs == null)
{
custs = _repository.GetAll();
if (custs != null && custs.Count() > 0)
{
double timeout = 600000d;
HttpRuntime.Cache.Insert("Customers", custs, null, DateTime.UtcNow.AddMilliseconds(timeout), System.Web.Caching.Cache.NoSlidingExpiration);
}
else
{
throw new NullReferenceException();
}
}
return custs;
}
public void Add(Customer value)
{
throw new NotImplementedException();
}
public void Update(Customer value)
{
throw new NotImplementedException();
}
public void Delete(Customer value)
{
throw new NotImplementedException();
}
public CachedCustomerRepository()
{
}
[Inject]
public CachedCustomerRepository(IRepository<Customer> repository)
{
_repository = repository;
}
}
public class CustomerRepository : IRepository<Customer>
{
public Customer Get(object id)
{
Customer cust = new Customer();
IList<Customer> custs = GetAll();
if (custs != null && custs.Count > 0)
cust = custs.FirstOrDefault(c => c.Id == int.Parse(id.ToString()));
return cust;
}
public IList<Customer> GetAll()
{
//Customer retrieval code
}
public void Add(Customer value)
{
throw new NotImplementedException();
}
public void Update(Customer value)
{
throw new NotImplementedException();
}
public void Delete(Customer value)
{
throw new NotImplementedException();
}
public CachedCustomerRepository()
{
}
}
Configuré un NinjectModule como este:
public class ServiceModule : NinjectModule
{
public override void Load()
{
Bind<IRepository<Customer>>().To<CustomerRepository>();
}
}
y he modificado los NinjectMVC3.cs en la carpeta AppStart para obtener el módulo de la hora de crear el kernel:
private static IKernel CreateKernel()
{
var kernel = new StandardKernel(new ServiceModule());
RegisterServices(kernel);
return kernel;
}
En mi controlador estoy usando esto:
public ViewResult Index()
{
IRepository<Customer> custRepo = new CachedCustomerRepository();
return View(custRepo.GetAll());
}
sopla en la línea _repository.GetAll()
en mi CachedCustomerRepository
.
He establecido un punto de interrupción para asegurarme de que el CreateKernel()
se está ejecutando y obteniendo los enlaces, que es. No estoy seguro de por qué la inyección no está sucediendo. Otra nota al margen, no sé si es importante o no, el IRepository, los repositorios y el tipo concreto se encuentran en una biblioteca de clases separada y se mencionan en la aplicación web mvc3. Tanto la aplicación web como la biblioteca de clase tienen una referencia a Ninject y la aplicación web también tiene una referencia a Ninject.MVC3. La creación del enlace y del kernel está teniendo lugar en la aplicación web.
+1 por la frustración que todos experimentan al aprender a utilizar la inyección de dependencia. – TheCloudlessSky