【问题标题】:Servicestack - Inject class that have constructorServicestack - 注入具有构造函数的类
【发布时间】:2013-12-20 03:26:31
【问题描述】:

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

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

【问题讨论】:

  • 另一个答案是关于在 AppHost.Configure() 方法中设置注入的依赖项。我从未使用过 ServiceStack,但它看起来像是非常标准的依赖初始化。您想要做的是尽可能使用构造函数注入。但是在构造函数中使用类似的其他类似乎您可能需要重新考虑设计。
  • 实际上我在谈论配置(顺便说一句,我编辑了我的问题并添加了配置)。实际上,我已经考虑过构造函数注入(并尝试过),但问题是,BaseRepository 类具有一些通常由 IoC 注入的依赖关系,如果 IoC 未初始化,则它也不会注入。跨度>
  • 这不应该是你的问题。只需确保首先注册存储库的依赖项即可。 AppHost.Configure() 应该在您第一次使用存储库之前运行。如果你有循环依赖,你需要调整你的设计。
  • 你提到调整设计,你能分享一下如何调整循环依赖吗?

标签: c# dependency-injection servicestack funq


【解决方案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();
    }
}

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

【讨论】:

  • 感谢您跟进您的问题,很好。
猜你喜欢
  • 1970-01-01
  • 2011-02-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-24
  • 1970-01-01
  • 2018-02-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多