Overriding property in shared project class

最后都变了- 提交于 2021-02-10 14:37:00

问题


Ok team,

Quick summary so you understand my question. We have an MVC app (Proj.MVC) that references a shared project (Shared.MVC). The shared project contains Controllers (BaseController & ApiController), Context, and Session Manager as those will be used by other projects. BaseController & ApiController have a reference to SharedContext and SharedSessionManager.

However, some project may need to add additional calls to Context and Session Manager. Now my problem is, I can use Interfaces so that new classes in Proj.MVC can swap out SharedContext with ProjContext and any inherited controllers can interchange the context type, but BaseController is still using SharedContext. Further all the Shared Controllers are using the SharedContext. So now 'new' logic is using the ProjContext & ProjSessionManager, while all the shared logic is using SharedContext & SharedSessionManager.

So my question is. How do I 'force' ProjContext/Session down to my Shared Controller? Pulling the Controllers out to Proj.MVC defeats the reuse.

namespace Shared.MVC
{
    public abstract class BaseMVCController: Controller
    {
        protected SharedContext DB;     
        protected SharedSessionManager SessionManager;
        
        protected override void Initialize(RequestContext requestContext)
        {
            base.Initialize(requestContext);
            DB = new SharedContext();   //This is being triggered on startup. Likely because HomeController inherits from BaseMVCController
            SessionManager = new SharedSessionManager(DB);
        }
    }
    
    public abstract class SharedApiController : ApiController
    {
        protected ISharedContext DB;
        protected SharedSessionManager SessionManager;
        
        protected override void Initialize(HttpControllerContext controllerContext)
        {
            base.Initialize(controllerContext);
            DB = new SharedContext();
            SessionManager = new SharedSessionManager(DB);
        }
    }
    
    public class SharedSessionManager : ISessionManager
    {
        protected readonly ISharedContext DB;
        
        public SharedSessionManager()
        {
            DB = new SharedContext();
        }
        public SharedSessionManager(ISharedContext myContext)
        {
            DB = myContext;     //This is being called from the BaseMVCController.Initialize method
        }           
    }

    public class SharedContext : DbContext, ISharedContext
    {
       public SharedContext() : base("contextName")
       {
       }
       public virtual DbSet<MyType> MyList { get; set;}
    }
}

来源:https://stackoverflow.com/questions/64122746/overriding-property-in-shared-project-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!