Access web.config from separate Class Library?

前端 未结 6 1354
轻奢々
轻奢々 2020-12-16 15:01

I\'m looking for a good way to achieve the following:

I have a web application (MVC 3), with a separate Class Library that contains the back-end logic of a CMS that

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-16 15:56

    I have exactly the same setup with a FOSS project I'm involved with. It contains everything (even the Controllers and Global.asax.cs) in the 'Core' class library.

    There's plenty of valid solutions, the one I opted for was to create a Settings class which is essentially a set of static properties, inside which you have:

    public static string ConnectionString
    {
            get { return ConfigurationManager.ConnectionStrings["MYAPP"].ConnectionString; }
    }
    

    Note: make sure your class library has System.Configuration added as a reference.

    Inside your Application (the class derived from HttpApplication) you pass the settings across, although there is nothing to stop you tighly coupling the NH setup with the settings class:

    protected void Application_Start()
    {
            AreaRegistration.RegisterAllAreas();
            RegisterRoutes(RouteTable.Routes);
            SetupNHibernate();
    }
    
    public virtual void SetupNHibernate()
    {
            NHibernateRepository.Current.Configure(RoadkillSettings.DatabaseType, Settings.ConnectionString, false, Settings.CachedEnabled);
    }
    

    If this is any use to you, the source is here.

提交回复
热议问题