You are on page 1of 17
How to create a modular web application in C# MVC B Scenario When a web application has multiple modules (or sub-applications/ features) it tends to get larger. So, the more modules you plug in your application, the more complex it becomes to partition and maintain the code, ‘What is the trick to solving this? A solution for the above problem is to develop application modules independently, without any direct dependencies among them and also on the main application code. Developers should always opt for a modular solution, in which larger modules are easily maintained over time, separately. Once each module is ready for integration, they could be then plugged into the main application with little to no adjustment of the same. So in short the structure of a complex asp.net MVC application can be very easily maintained using areas. The concept of this is to allow us to breakdown a large complex application into a several small sections called areas, ‘These areas can have their own set of: 1. Models 2. Views 3. Controllers 4, Routes In this article we are going to develop an ASP.NET MVC application that contains loosely coupled modules (independent to main application), which we will further plug in the main application, Benefits of this approach This approach is extremely useful for product development. Utilizing this approach, each module may be developed and deployed for the product separately. This helps in building different versions of the product, like basic, professional, premium, and enterprise versions. It also enables product developers to create the isolation required to ii Build separate installers with the required features for each different version, ii A master setup which can only install defined features as per license key used during installation, or i Some other configuration that requires the modular separation technique. Demo for a Modular App Here we will create a web application that contains the following modules: Sale Purchase Maintenance + Marketing Stock “Import Export Step 1: Open Visual Studio 2015 and create an ASP.NET MVC project as follows. Give it a meaningful name (in my case I have used MVCPluggableDemo).. | DT famevedtS —_» Sot Odaut © Be ons spn ‘we ts preven Secon prereset ee eee omens sete phat cote hater. = + vsteane Peeeryourcretenae Vile ‘oem alans omnec your pect, Moose (Wipes bgt 504 Seer Helpme undestand eten ahs Fre Payne JanSciet Typeset Once ‘Slice pennant fem, tone tection ‘hurt docu il eo Bree ston Salulen ene vCPugutiedeme | Selects templates ASP.NET 45 Tempter Gos fm Empty WebForms MVC WebAPL_— ‘Single age Aoplcation mo Sa fe APLpo Aur Mebie mon one | ASP.NET Templates gi GeLASP.NETSAC ‘iid elds med oes deve FlWenFome [mvc Fl web ae EL Ads unittest: Test prjectrame: Wi/CPluggebleDeia Tests ‘Once it is created, your solution should look like this: ‘An empty project template for creating ASP.NET apelcations This templete does net have ary contentin Leaen more ‘Authentication: No Authentication © Microsoft Aru (2) Hecin necoud Web pp @ o-s¢aB es Search Solution Explorer (Ctrl) [5 Solution MVCPluggableDemo' dl oroject) acs > > F Froperties References App Data App Start i Controliers SS Models scripts i Views 4D Applicationtnsights.config I Global.asax AB) packages.config Di Web. contig Solution Explorer RTE Step 2: Right-click on the ‘Controllers’ folder and select “Add -> Controller”. Name it HomeController, and select “Empty MVC Controller” for the template: Contiollername | HomeContller Right-click on the Index method of the controller and select “Add View”. Using defaults, create the Index view for HomeController to form the landing page for the application: Viewname: Index Template; Empty (without model) Modelciass | Options: (F Create as parial view Reference sagt Ubratin Use a layout page: (Leave empty if tis set in a Razor_viewstart fle) Step 3: Now edit the highlighted section in_Layout.eshtml (under the Views\Shared folder) in order to create ‘menu items pointing to the desired modules: o-o/o-taw|2=e>] camel Ee 8 [5 (Ra EER Step 4: Run the application and you will get the output as follows: Fe Soares Home page ‘ow we will focus on creating separate modules for our application and then plug them into the main one, Step 5: Right-click on the main application project title (as in our case MVCPluggableDemo) in the Solution Explorer and select “Add->Area” from the context menu. This will create a basic folder structure for the Area framework. Specify “Sale” as Area name and click “Add” ‘Then we have a folder solution structure that looks like: Ee Gl e-staBplos Search Solution Explorer (Ctr) P- {51 Solution ‘MVCPluggableDemo’ (1 project) 4. EF] MVCPuggableDemo & Propattiee References Sl App_Date i App Start ‘a Areas 4 Gi Sale Contralles SS Models 4 Views Shared web. contig )c* SaleAreaRegicration cs (i Content ‘sl Contrllers ) c HomeControlercs (i forts Il Models scripts Gl Views 4G) Home {@ Index.eshtml 4 Gl Shared {1 _Layout.eshtml 21 _ViewStertcshtr Di weo.contig {B) Applicationinsights.contig 5) Globalasax $8) packagescontig (Bi Web.config Solution Explorer FESS Step 6: ‘Take a backup of the SaleAreaRegistration.es file. This file will be needed later on when we add the Sale module to the solution as a separate project. Now remove the Sale subfolder from the Areas folder, keeping the Areas folder in place. Next add the new pluggable module for “Sale”, right-click on the solution and choose “Add-> New Project”. Select Empty ASPNET MVC Application ‘Name to project “Sale” Set Location as “...\ MVCPluggableDemo\MVCPluggableDemo\Areas\” A new project should be created in the Areas folder (previously created), cet “ReTFamerektS —_=|Sot by Diu [sxc nite Temps 2 sate 4 Vawter projet tempi for eeting ASO NET Widens Septensors Youcen cule SPT Wes Fema bt ren aPLopietns and (Q Fereatonnsgh GB Ad Appcasonbsighs to ct Ina he preabon ih SD rdusagectebeutyurappcaton | (eames pstaontnaaions| | » atone “A. Peter you cede # vioscrs ‘Youcan sae comme you pect aL sewer {opptcaton nag ate Petes Isr emis appeal » ypeserpt see ld Resestar # Onioe ‘Slcksio ga slneanifidtenaies, inte Dccamerts Vil So 205 rjc MVCPaggtieDenc\MNCPuggetlceme rar = After this step, your solution should look like the one below: @\o-SO6Fa s= Search Solution Explorer (chit) P- fl Solution MMVCPluggebleDemo' (2 projects) 4] MVCPluggableDemo > & Properties > ta References pp_Data > App ster Dm Content 4 © Controfers > © HomeContrllecs 1S fonts scripts Views 4G Home 9 Indexccshtral 4) Shared {)_Layoutshtml (e)_ViewStartcshtml B webconfig 4D Applicationinsights.config BI Global.asax (D packages.config Di Web. config > & Properties bm References Wl App_Data App Start © Controiers 1S Models scripts i Views 2) Applicationinsights.config A Globatasax 1B) packages.contig $B) Web.contig Solution Explorer SEES ‘As we saved new project Sale under the Areas folder, it appears as hidden folder under the MVCPluggableDemo/Areas folder in the Solution Explorer: @|e-sé6al|s— Search Solution Expiorer (Cts) [Seearne [1 Solution 'MVCPluggableDemo” PsWar & Properties i References SS App Dets SS App Stat \G) Areas > £7 Sale © bin © Content ‘Controllers Dc HomeControllerics fonts SS Models obj scripts ‘sl Views 4 i Home {1 Index.cshtmal Shared {21 _Layout.cshtmi 181 _ViewStart.cshiml Pi web.config D. Applicationinsights.config 2 Globatasex 1D pockages.config > 2 Web.contig Bl sale F Properties 1 References © App Data App Start bin Controllers tS Models obj 1 scripts ie Views (2) Applicationinsights.config 8) Global. asax 4 packages.config Web config Solution Explorer aE Step 7: Adjust the MVCPluggableDemo’s RouteConfigces file to properly add the correct namespace ‘overload to the routes. MapRoute() method: ‘We will also use the other overloaded version of routes. MapRoute() method which takes the namespace of the Controller. BUDE /D UE les lm peewee label ¥ain IS, enchagecen eae Jo Ratatat using systenuebswet sing Systew Mab. Routings = nowbspace mcpluggabl een fi pblie class noutecontie c pubic stati vid tagistarote(sovtcel ection een routes. tgnoreRoute("[resource}-axd/(*pathinto}") roves. saptetet feoerotier) faction / (6), fev €coellen schon) Stton « “ines 2 = uriroroneter opto fon Serin(] (Serloggsbeoee nro } & , , ) Step 8: Set the output directory of Sale project to ..\.\bin\ so that it’s compiled DLLs are placed in the bin directory of the MVCPluggableDemo application: es, Soren (ngs) hen incr ereniocnsenny Be IES Setting related to connection strings, authentication, membership, role manager, profile, and session state are going to be placed in the web.config of your root directory. So remove all these section from the sale’s web.config. Step 9: Create the Sale controller in the Sale project. Create an Index view and place the content “Welcome to Sales Module” in its header. Step 10: Now add SaleAreaRegistration.cs file (Backup file from step 6) to the root directory of the Sale project and change its namespace to MVCPluggableDemo; use the overloaded version of context. MapRoute() method which accepts the namespace of the controller to use as follows: 6 ie =eII eo [Ee] a etree, ‘aneepace tePluggableoox 2) gublic elas salearoanegtstration + arcanegistration c F fublse ovarctse steing Areaane t ‘ 5 } public override void nagistertrea(sccaTegistrationcontent context) ‘ context mote Sale/(eaneroLier}/{aetion)/(44)", ren (controller="sale", action ~ "index", 4d ~ velParanster.optional }, few string] { “sale.controllers” Step 11: ‘Now build the solution and check the MVCPluggableDemo\bin folder and you will have the compiled DLLs for the Sale module there: Name Datemodified Type sie BE rosiyn /2/2015554PM — Filefoldes 3D Applicetioninsights /2/205617 PM XML Configuratio, 5x6 @ Miciosoft ALAgent Intercept all 2/2010549 PM Application extent. ‘ant KB (| Miciosof.ALDependencyCollectordll ——_£/2/2026549PM Application sean. 55KB | Microsoft..DepandencyCelletor £/2/2015549 PM XML Decument 5OKe (8) MicrosoftALPerfCounterCollectordll §——&/2/201859 PM Azplicabon extens. cid |) MicrosoftAlServerTelemetryChanneldll £/2/2010550 PM Azplicaton extens. 78Ke |S] Microsoft AlServerTelemetryChannel ——/2/2015580 PM XML Decurent 9K (9) Microsoft AL Web cl @A/IESS0PM —Acplication extens SLB 2 Microsoft AL Web /2/2015550 PM XML Docurnent 19K6 2 Miciosoft ALWindowsServerall 2/2010550 PM Application extent. 35Ke Miciosof.AlWindowsServer 8/2/20265:50PM XML Document KB | Microsoft Applcatininights dl /2/2015549PM Applicaton ecens. 7 {2} Microsoft Applicationinsights 18/2/2015549 PM XML Document 1 |) Microsoft CodeDom Providers DotNetCe.. £/2/2018589 PM Acplicaton extens. Ke Microsoft.CodeDomProvidersDatNetCon, §/2/2025549PM XML Document 2B |S) Microsoft Web infrastructure dt @A/WIESAIPM —Acplication extens oe & MUCPluggableDemo.l /2/2016642PM Application extens 76 £5 MUCPluggableDemo. 8/2/2015550 PM XML Configuratio, 3K8 ] MvcPiuggabledems.pab 8/2/202662PM PDB Fite wae (a Saledtt /2/201563 PM Applicaton eens. 76 29 Saleatt 2/2015647 PM XML Configuratio, ake _ Salepdo g/2/201b643PM PDB Fite we 3) SjstemWebHelpersll 8/2/2025 549M Applicaton eden. 127 Ke Sytem WebiHelpers @2/016549 PM XML Document 48 & System WebMvcll /2/2016549 PM Application extens S58 KB ©) SpstemWeb Mie '8/2/2015549 PM XML Document 931 KB (System WebsRazor.t 8/2/2026 549 PM Application seen. 265 KB System Web.Razor /2/2015589PM XML Document 510 KB <2] SystemWebiWebpages Deploymentall —£/2/201959PM —_Agplication eens. ae |) System.Web. Webpages Deployment §/2/2018589 PM —_XNIL Document Ske 3) SystemWeb.Webpagesi 8/2/2025 5:49PM Applicaton eden. 27 Ke |S) SytemWebiWebpages Razor @ALWESAIPM —Acplication extens 23K8 /2/2016549PM_ XML Document KB '8/2/2015549 PM XML Document 730 KB Step 12: ‘Now run the application! If you have followed all the steps correctly, it will be working as expected Home page BES ¢ el siaioie) | Real Welcome to Sales Module BE ¢lelsigiaiei | Real You can follow the same steps and create other larger modules separately and plug them in to your application. Isn’t it simple yet such a powerful feature when it comes to product development? Post your comments, doubts and queries below. The demo application is also available for download here. Happy coding!

You might also like