Unity和OData(WCF数据服务)
本文关键字:数据 服务 WCF OData Unity | 更新日期: 2023-09-27 18:00:20
我正在尝试将Unity与我的WCF数据服务(OData)一起使用。我有这样的代码:
public class PatientService : DataService<IPatientRepository>
我希望unity在运行时为IPatientRepository注入正确的对象(无论是真实的PatientRepository还是我用于测试的伪造对象)
我已经做了:
IUnityContainer container = new UnityContainer();
container.RegisterType<IPatientRepository, MyEntities>();
但当我跑步时,我会得到:
服务器在处理请求时遇到错误。异常消息为"无法创建数据提供程序"。为"PatientService"中的数据源键入"RepositoryInterfaces.IPatientRepository"是抽象的
有没有办法注入这种依赖性?还是我必须把真正的课放在那个位置?
CreateDataSource方法是我在请求生命周期中发现的组成对象图的最早点。在这里,它被用作复合根。Bootstrapper是一个调用Unity配置的助手类,无论是从XML还是在代码中加载。
public class PatientService : DataService<IPatientRepository>
{
public static void InitializeService(DataServiceConfiguration config)
{
// TODO: set rules to indicate which entity sets and service
operations are visible, updatable, etc.
...
}
[WebGet]
public IQueryable<Patient> Patients()
{
return from p in CurrentDataSource.Patients select p;
}
protected override IPatientRepository CreateDataSource()
{
IUnityContainer container = new UnityContainer();
Bootstrapper.Initialise(container);
return container.Resolve<IPatientRepository>();
}
}
所以@Roy将您指向CreateDataSource()方法是正确的。但是,应该避免使用ServiceLocator作为类或模式。不幸的是,微软几乎用ServiceLocator和DependencyResolver这样的类强迫每个人都使用ServiceLocator。
WCF数据服务不知道您的Container,因此无法调用它来查找您传递的接口的实现。
同样,Container可以进行构造函数注入,但不能在DataService<T>。
因此,据我所知,没有办法将DataService与Interface一起使用,然后注入实现。
EDIT:正如Vitek在评论中指出的那样,应该只将类声明为DataSource<T>使用接口,然后重写CreateDataSource()方法。在该方法中,您可以对IYourInterface的实现进行ServiceLocator调用:
var myService = ServiceLocator.Get<IYourInterface>();
当然,这需要为服务位置配置容器。
模式&Practices小组显然已经为ServiceLocator模式实现了Unity适配器,请参阅http://commonservicelocator.codeplex.com/wikipage?title=Unity%20Adapter&referringTitle=主页&ProjectName=公共服务定位器。
有关服务定位器模式的更多信息,请参阅http://msdn.microsoft.com/en-us/library/ff648968.aspx.