JumpStart # 20– Do not include config data in class libraries, instead inject from invoking application

Most of the Junior developers tend to put up there configuration sections of class libraries (DLL’s) along with them. The typical class libraries (for example – Data Access Layer, Business Layer etc) should be configured from the executing assembly. Having config in the same DLL’s would hinder their purpose of re-usability.

IMPORTANT – Some kind of Managed DLL’s and other standalone DLL’s can have files included in them as ember resources. It is up to the requirement and development context to decided whether to have or have not the config sections along with libraries.

Lets quickly look into a sample to code to have config specified from executing application. Create a Class Library (with name ClassLibrary1) and in the by default Class1.cs, have the following code –

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ClassLibrary1
{
    public class Class1
    {
        public static string GetEmail()
        {
            return Settings.Email;
        }
    }

    public static class Settings
    {
        public static string Email
        {
            get { return ConfigurationManager.AppSettings["email"]; }
        }
    }
}

 

Build this class library. Now add a MVC WebApplication and then add this class library dll as a reference to the MVC Web project. In Web.Config file of MVC project, add the following setting in appsettings node.

<add key="email" value="rami.ramilu@gmail.com"/>

Add a new controller to the controllers folder, name it as MyController –

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcApplication1.Controllers
{
    public class MyController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Email = ClassLibrary1.Class1.GetEmail();
            return View();
        }

    }
}

 

Add a corresponding View to it –

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
        <div>@ViewBag.Email</div>
    </div>
</body>
</html>

 

Now simply execute the page –

image

You may also like...

2 Pingbacks/Trackbacks