[英]Servicestack - Inject class that have constructor
我有上課,有一些這樣的屬性注入:
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-依賴性似乎不會被注入?
我需要將構造函數移至Apphost.config()中。我的問題是,如何將此類構造函數移至apphost.config()中? 如果我有很多這樣的課程,該如何處理?
好的,這已經有一段時間了,當我提出問題時,我通過將屬性注入更改為構造函數注入來解決此問題,如下所示:
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);
}
}
我將注入移動到Service:
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();
}
}
我希望有另一種方法,但這只是我能想到的解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.