Servicestack - 具有构造函数的Inject类

时间:2013-12-20 03:26:31

标签: c# dependency-injection servicestack funq

我上课有一些属性注入:

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()中? 如果我有很多这样的课程,如何管理?

1 个答案:

答案 0 :(得分: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();
    }
}

我希望还有另一种方式,但这只是我能想到的解决方案。