2011-01-06 93 views
1

我正在使用webforms,我想知道如何刪除對倉庫的後續具體引用。在過去,我使用MVC城堡windsor,但我不認爲我可以在這裏使用它?背後從構造函數中刪除依賴關係

代碼:

ICustomerRepository repos; 

public Workout_Admin() 
    // here is the offending concrete implementation 
    : this(new SqlCustomerRepository()) { } 

public Workout_Admin(ICustomerRepository repos) 
{ 
    this.repos = repos; 
} 

修訂---

我已經更新的靜態方法suggeted,以及添加額外的代碼來溫莎工廠

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的文件夾。這裏是相關CONFIGS

<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.Factory.CommonServiceLocatorPageHandlerFactory 'YourFit'。

我知道我很可能真的很愚蠢。非常感謝你在這方面的時間。

回答

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將告訴您如何做到這一點(爲溫莎城堡,只是改變在GetInstance方法調用溫莎容器中的代碼)。請注意,您需要爲此完全信任。

UPDATE

您可以更改本文介紹以下的private static object GetInstance(Type type)方法:

public static IWindsorContainer Container; 

private static object GetInstance(Type type) 
{ 
    return Container.Resolve(type); 
} 

在您的應用程序的啓動路徑(其中配置了溫莎城堡容器)你比必須設置靜態Container屬性:

// Create 
IWindsorContainer container = ... 

// Configure 

// Set container to page handler factory 
CommonServiceLocatorPageHandlerFactory.Container = container; 

我希望這是有道理的。

+0

你也可能想看看這個SO問題:http://stackoverflow.com/questions/293790/how-to-use-castle-windsor-with-asp-net-web-forms。 – Steven 2011-01-06 12:37:51