C# ASP.NET Dependency Injection with IoC Container Complications

前端 未结 1 1046
暗喜
暗喜 2021-01-16 05:36

I apologise for the length, and I know there are some answers on this but I searched a lot and haven\'t found the right solution, so please bear with me.

I am trying

相关标签:
1条回答
  • 2021-01-16 06:13

    Perhaps I misunderstand your problems, but the solution seems fairly simple to me: promote the IView to a property on the Presenter1:

    class Presenter1
    {
        public Presenter1(IRepository<User> userRepository)
        {
        }
    
        public IView1 View { get; set; }            
    }
    

    This way you can set the presenter on the view like this:

    public Presenter1 Presenter { get; set; }
    
    public MyPage1() 
    {
        ObjectFactory.BuildUp(this);
        this.Presenter.View = this;
    }
    

    Or without property injection, you can do it as follows:

    private Presenter1 _presenter;
    
    public MyPage1() 
    {
        this._presenter = ObjectFactory.Resolve<Presenter1>();
        this._presenter.View = this;
    }
    

    Constructor injection in Page classes and user controls will never really work. You can get it to work in full trust (as this article shows), but it will fail in partial trust. So you will have to call the container for this.

    All DI containers are thread-safe, as long as you don't manually add registrations yourself after the initialization phase and with some containers even that is thread-safe (some containers even forbid registering types after initialization). There would never be a need to do this (except for unregistered type resolution, which most containers support). With Castle however, you need to register all concrete types upfront, which means it needs to know about your Presenter1, before you resolve it. Either register this, change this behavior, or move to a container that allows resolving concrete types by default.

    0 讨论(0)
提交回复
热议问题