Question

I Have class that have some property injection like this:

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

And used by Services like this:

public class TheServices : Service
{
    public MyRepository Repo { get; set; }

    public object Post(some_Dto dto)
    {
        return Repo.MethodUsingUid();
    }
}

And my Apphost.configuration looks like this:

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

I know it will not injected because it will created before funq have chances to inject. and according to this answer: ServiceStack - Dependency seem's to not be Injected?

I need to move the constructor into Apphost.config() My question is, how I move this class constructor out into apphost.config()? and how to manage that if I have many class like that?

Was it helpful?

Solution

Ok, so it's been a while when I create my questions, I resolve this with changing from property injection into constructor injection like this:

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

And I move the injection to 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();
    }
}

I Hope there's another way, but it's only solutions that I can think.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top