Thursday, July 25, 2013

ASP MVC and Spring.Net basic example

1. First step, launch Manage NuGet Packages

2. Search for Spring and install the features presented below



3. Now all references you need are added to your project for using Spring.Net, but I prefer to do something more and add Spring.CodeConfig



4. By using Spring.CodeConfig, we have the chance to change xml configurations with .Net code configurations


4.1.Create a HelloService interface

    public interface HelloService
    {
        string sayHello(string name);
    }

4.2. The implementation of HelloService

    public class HelloServiceImpl:HelloService
    {
        public string sayHello(string name)
        {
            return "Hello " + name;
        }
    }

4.3. The last step...create the application context and inject the service in you controller


**Create the configuration for Service injection
    [Configuration]
    public class ServiceInjectorConfiguration
    {
        [Definition]
        public virtual HelloService GetHelloService()
        {
            return new HelloServiceImpl();
        }
    }

**Update Global.aspx

    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            ControllerBuilder.Current.SetControllerFactory(typeof(SpringControllerFactory));

            var appContext = new CodeConfigApplicationContext();

            appContext.ScanAllAssemblies();
            appContext.Refresh();

            Application["appContext"] = appContext;
        }
    }

**Use your HelloService in controller
    public class HomeController : Controller
    {
        //
        // GET: /Home/
        private HelloService service;
        private GenericApplicationContext appContext;

        public ActionResult Index()
        {
            appContext = (CodeConfigApplicationContext)HttpContext.Application["appContext"];

            service = (HelloService)appContext.GetObject("GetHelloService");

            ViewBag.HelloMessage = service.sayHello("Alex");
            return View();
        }

    }

ASP.NET MVC, .Net, MVC, HTML helpers, Spring.net, Spring, services, ViewBag, applicationContext, dependency injection, spring code config

No comments:

Post a Comment