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

インジェクションを 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();
    }
}

別の方法があることを願っていますが、私が考えることができるのは解決策だけです。

于 2013-12-26T02:43:14.080 に答える