1

我有一些像这样的属性注入的类:

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

4

1 回答 1

2

好的,所以当我创建问题已经有一段时间了,我通过从属性注入更改为构造函数注入来解决这个问题,如下所示:

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();
    }
}

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

于 2013-12-26T02:43:14.080 回答