Base solution for your next web application
Open Closed

SettingManager in ControllerBase Constructor #1962


User avatar
0
sayram created

Can't we use AbpController.SettingManager in Constructor of ControllerBase?

protected IndexControllerBase()
        {
            LocalizationSourceName = IndexConsts.LocalizationSourceName;
            ViewBag.Theme = SettingManager.GetSettingValue(IndexSettingProvider.CurrentTheme); 
        }

Returns "Object reference not set to an instance of an object."

I'm trying to pass current theme setting to all view via ViewBag.

this is the _Layout file in shared dir.

@{ 
    Layout = ViewBag.Theme;
}

@RenderBody()

@RenderSection("styles", required: false)

@RenderSection("scripts", required: false)

2 Answer(s)
  • User Avatar
    0
    sayram created

    I found a working "hack" to pass data to all views.

    I created a service named ISettingService and implemented here.

    public class SettingService : ApplicationService, ISettingService
        {
            public string GetTheme()
            {
                return SettingManager.GetSettingValue(IndexSettingProvider.CurrentTheme);
            }
        }
    

    I inject ISettingService in ControllerBase.

    public abstract class IndexControllerBase : AbpController
        {
            private readonly ISettingService _settingService;
    
            protected IndexControllerBase(ISettingService settingService)
            {
                _settingService = settingService;
    
                LocalizationSourceName = IndexConsts.LocalizationSourceName;
                ViewBag.Theme = _settingService.GetTheme();
            }
    }
    

    And in each controller i created their constructor

    public class HomeController : IndexControllerBase
        {
    
            public HomeController(ISettingService settingService): base(settingService)
            {
    
            }
    
            public ActionResult Index()
            {
                return View();
            }
    
    	}
    

    this way is works. But the ugly way i believe.

  • User Avatar
    0
    manuel created

    Maybe too late, but if you want to improve your code you can:

    public IndexControllerBase : AbpController
    {
        protected override void Initialize(RequestContext requestContext)
        {
            // inject with IOC the service
           // happily use the service :)
            base.Initialize(requestContext);
        }
    }
    

    But, answering your question:

    Can't we use AbpController.SettingManager in Constructor of ControllerBase?

    The service needs to be resolved and injected in some way, be careful when using services in the constructor, the services that depend on session specifics could not work fine there.