2013-12-20 21 views
1

我有一個有一定財產注入這樣的類:Servicestack - 注射類具有構造

public class MyRepository 
{ 
    public IBaseRepository BaseRepository { get; set; } //Injected By IoC 
    public IUid Uid { get; set; } // Injected By IoC 

    private static AnotherClass _anotherClass; 


    public MyRepository() 
    { 
     _anotherClass = BaseRepository.Db.SingleOrDefault<AnotherClass>(); 
     //another logic in here.... 
    } 

    public string MethodUsingUid() 
    { 
     return Uid.SomeMethodHere(_anotherClass); 
    } 
} 

和使用服務是這樣的:

public class TheServices : Service 
{ 
    public MyRepository Repo { get; set; } 

    public object Post(some_Dto dto) 
    { 
     return Repo.MethodUsingUid(); 
    } 
} 

而且我Apphost.configuration看起來像這樣:

container.Register<IDbConnectionFactory>(conn); 
container.Register<IBaseRepository>(c => new BaseRepository(){ DbFactory = c.Resolve<IDbConnectionFactory>()}).ReusedWithin(ReuseScope.Request); 

container.Register(
       c => new MyRepository() { BaseRepository = c.TryResolve<IBaseRepository>(), Uid = c.TryResolve<Uid>() }); 

container.RegisterAutoWired<Uid>().ReusedWithin(ReuseScope.Request); 

我知道它不會注入,因爲它會在funq創建之前有機會注入。 並根據這樣的回答:ServiceStack - Dependency seem's to not be Injected?

我需要構造移動到Apphost.config() 我的問題是,我如何移出這個類的構造函數爲apphost.config()? 以及如果我有很多這樣的課程,該如何管理?

+0

另一個答案是關於在AppHost.Configure()方法中設置注入的依賴關係。我從來沒有使用過ServiceStack,但它看起來像非常標準的依賴關係初始化。如果可能的話,你想要做的是使用構造器注入。但是在構造函數中使用類似的其他類似乎你可能想要重新考慮設計。 – crad

+0

其實我在談論配置(並且謝謝btw,我編輯了我的問題並添加了配置)。實際上,我已經考慮過構造函數注入(並嘗試過),但問題是,BaseRepository類有一些通常由IoC注入的依賴項,並且如果IoC未初始化,那麼它將不會被注入。 – reptildarat

+1

這不應該是你的問題。只要確保先註冊存儲庫的依賴關係。 AppHost.Configure()應該在您首次使用存儲庫之前運行。如果你有循環依賴,你需要調整你的設計。 – crad

回答

1

好了,它已經有一段時間,當我創建我的問題,我用來自物業注入變更爲構造函數注入是這樣解決的:

public class MyRepository 
{ 

    private static AnotherClass _anotherClass; 
    private readonly IBaseRepository _baseRepository; 
    private readonly IUid _uid; 

    public MyRepository(IBaseRepository _baseRepository, IUid uid) 
    { 
     _baseRepository = baseRepository; 
     _uid = uid; 

     _anotherClass = BaseRepository.Db.SingleOrDefault<AnotherClass>(); 
     //another logic in here.... 
    } 

    public string MethodUsingUid() 
    { 
     return _uid.SomeMethodHere(_anotherClass); 
    } 
} 

我移動注射服務:

public class TheServices : Service 
{ 
    public IBaseRepository BaseRepository { get; set; } //Injected By IoC 
    public IUid Uid { get; set; } // Injected By IoC 

    public object Post(some_Dto dto) 
    { 
     var Repo= new MyRepository(BaseRepository, Uid); 
     return Repo.MethodUsingUid(); 
    } 
} 

我希望有另一種方式,但這只是我能想到的解決方案。

相關問題