我有以下课程:
SuppliersRepository.cs (使用定义方法的界面):
public class SuppliersRepository : BaseRepository,ISuppliersRepository
{
public IEnumerable<Supplier> GetSuppliersByCoordinates(double latitude, double longitude)
{
using (IDbConnection connection = OpenConnection())
{
const string query = "SELECT ID=SupplierID,Name=Suppliername FROM suppliers WHERE dbo.Distance(@latitude,@longitude,latitude,longitude) < 15 AND latitude IS NOT NULL AND longitude IS NOT NULL";
return connection.Query<Supplier>(query, new { latitude = latitude,longitude=longitude });
}
}
}
BaseRepository.cs (使用定义方法的界面)
public abstract class BaseRepository: IBaseRepository
{
public IDbConnection OpenConnection()
{
IDbConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["myconnection"].ConnectionString);
connection.Open();
return connection;
}
}
从global.asax.cs调用 Bootstraper.cs :
public static class Bootstrapper
{
public static void Initialise()
{
var container = BuildUnityContainer();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}
private static IUnityContainer BuildUnityContainer()
{
var container = new UnityContainer();
container.RegisterType<IBaseRepository, BaseRepository>();
container.RegisterType<ISuppliersRepository, SuppliersRepository>();
container.RegisterInstance<IHttpControllerActivator>(new HttpControllerActivator(container));
container.RegisterControllers();
return container;
}
}
两个控制器,第一个可以很好地解析存储库:
public class VenueController : MasterController
{
[Dependency]
public SuppliersRepository _SuppliersRepository { get; set; }
}
但是这个失败了:
public class AjaxController : Controller
{
[Dependency]
public BaseRepository _BaseRepository { get; set; }
}
抛出 System.InvalidOperationException:无法构造类型BaseRepository。您必须配置容器以提供此值。
知道我做错了什么吗?
答案 0 :(得分:2)
首先,在使用依赖注入时,最好是依赖于接口,而不是依赖于具体的类。我会将您的控制器更改为
public class VenueController : MasterController
{
[Dependency]
public ISuppliersRepository _SuppliersRepository { get; set; }
}
public class AjaxController : Controller
{
[Dependency]
public IBaseRepository _BaseRepository { get; set; }
}
其次,BaseRepository
是abstract
类。抽象类的实例无法构造,我认为这就是为什么当统一实际创建BaseRepository
时失败的原因。你应该注入具体的课程。
container.RegisterType<IBaseRepository, SomeConcreteImplementationOfBaseRepository>();
答案 1 :(得分:0)
您应该定义您的类以获取IRepository的属性,例如:
public class AjaxController : Controller
{
[Dependency]
public IRepository _BaseRepository { get; set; }
}
您的属性应始终根据接口而不是具体实现进行定义,否则您将自己与实现联系起来,从而使依赖注入的使用变得毫无意义!