我正在使用webforms,我想知道如何删除对存储库的后续具体引用。在过去,我曾使用温莎城堡和MVC,但我不认为我可以在这里使用它?
代码背后:
ICustomerRepository repos;
public Workout_Admin()
// here is the offending concrete implementation
: this(new SqlCustomerRepository()) { }
public Workout_Admin(ICustomerRepository repos)
{
this.repos = repos;
}
更新---
我已经将静态方法更新为suggeted,并将其他代码添加到windsor工厂
WindsorContainer container;
public WindsorControllerFactory()
{
container = new WindsorContainer(
new XmlInterpreter(new ConfigResource("castle")));
var controllerTypes =
from t in Assembly.GetExecutingAssembly().GetTypes()
where typeof(IController).IsAssignableFrom(t)
select t;
foreach (Type t in controllerTypes)
{
container.AddComponentLifeStyle(t.FullName, t,
LifestyleType.Transient);
}
CommonServiceLocatorPageHandlerFactory.Container = container;
}
持续出现的问题是从配置文件加载程序集。 CommonServiceLocatorPageHandlerFactory位于和程序集中,名为yourfit,名为factory的文件夹。这是相关的配置
<httpHandlers>
<add verb="*" path="*.aspx"
type="YourFit.Factory.CommonServiceLocatorPageHandlerFactory, YourFit"/>
</httpHandlers>
<handlers>
<remove name="UrlRoutingHandler"/>
<add name="CSLPageHandler" verb="*" path="*.aspx"
type="YourFit.Factory.CommonServiceLocatorPageHandlerFactory, YourFit"/>
</handlers>
,错误是:
无法从程序集“YourFit”中加载“YourFit.Factory.CommonServiceLocatorPageHandlerFactory”类型。
我知道我很可能真的很蠢。非常感谢你的时间。
答案 0 :(得分:1)
你可以这样做。但是,ASP.NET编译引擎需要一个默认构造函数,但您可以使其受到保护。您可以通过定义在重载(公共)构造函数中注入依赖项的自定义PageHandlerFactory
来在其他构造函数中注入依赖项。你的课程看起来像这样:
public class Workout_Admin : Page
{
ICustomerRepository repos;
protected Workout_Admin() { }
public Workout_Admin(ICustomerRepository repos)
{
this.repos = repos;
}
}
Here is an article向您展示了如何执行此操作(对于Castle Windsor,只需更改GetInstance
方法中的代码以调用Windsor容器)。请注意,您需要完全信任。
<强> 更新 强>
您可以将文章描述的private static object GetInstance(Type type)
方法更改为以下内容:
public static IWindsorContainer Container;
private static object GetInstance(Type type)
{
return Container.Resolve(type);
}
在应用程序的启动路径(配置Castle Windsor容器)中,您必须设置静态Container
属性:
// Create
IWindsorContainer container = ...
// Configure
// Set container to page handler factory
CommonServiceLocatorPageHandlerFactory.Container = container;
我希望这是有道理的。