Fun with ASP.NET MVC 3, MEF and NuGet (#comdaybe)


Published on

Published in: Technology
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • Demo01_MVC_DependencyResolverAdd a property to the HomeController for specifying the welcome messageAdd a class “SimpleDependencyResolver.cs”Implement IdependencyResolver (use snippets for some parts)    public class SimpleDependencyResolver        : IDependencyResolver    {        public object GetService(Type serviceType)        {            if (serviceType == typeof(Controllers.HomeController))            {                var controller = Activator.CreateInstance(serviceType) as Controllers.HomeController;                controller.MessageText = "Welcome, this text has been injected!";                return controller;            }            if (serviceType.IsInterface)            {                if (serviceType == typeof(IControllerFactory)) return new DefaultControllerFactory();                if (serviceType == typeof(IControllerActivator)) return null;                if (serviceType == typeof(IFilterProvider)) return GlobalFilters.Filters;                if (serviceType == typeof(IViewEngine)) return new RazorViewEngine();                if (serviceType == typeof(IViewPageActivator)) return null;            }            return Activator.CreateInstance(serviceType);        }        public IEnumerable<object> GetServices(Type serviceType)        {            return new object[] { GetService(serviceType) };        }    } Register dependencyresolver in App_Start:DependencyResolver.SetResolver(new SimpleDependencyResolver());
  • Demo02_MefContribCreate a new MVC application (application template)Add an IHelloWorldService    public interface IHelloWorldService    {        string Hello();    } Add a HelloWorldService    [Export(typeof(IHelloWorldService))]    public class HelloWorldService        : IHelloWorldService    {        public string Hello()        {            return "Hello from HelloWorldService!";        }    } Change HomeController     public class HomeController : Controller    {        private IHelloWorldService service;         [ImportingConstructor]        public HomeController(IHelloWorldService helloWorldService)        {            this.service = helloWorldService;        }         public ActionResult Index()        {            ViewBag.Message = this.service.Hello();             return View();        }         public ActionResult About()        {            return View();        }    } Run and fail…NuGet the MefContrib.MVC packageExplain the fact that it uses the /bin folder for part discoveryExplain the use of conventions
  • Initech.Components.Theming.DefaultThemeOpen solutionShow it’s nothing but a “plain old” MVC applicationRun the projectDemonstrate it does nothing, it’s just a template…Show the NuGet folder in Windows ExplorerOpen package.nuspec using NuGet Package ExplorerShow people around:Show the “Content” folder, this is where package contents will go. In this case, it will contain the Views, CSS and scripts.Show “lib”: it will contain assemblies (if appropriate for the package)Package.proj is the MSBUILD script that does the packagingOpen itSpecify some settings about what to copy and packageUpdate version number in nuspec fileRun nuget.exe on the nuspec fileAwesomeness!
  • Tonen aparte directoryTonen NuGet.ServerTonen
  • IniTech.TpsCoverSheetGeneratorCreate an empty MVC applicationAdd a library package reference to InitechThemeDefaultThemeUpdate _ViewStart.cshtml to use _InitechLayout.cshtmlAdd a HomeControllerAdd a viewRun the application to show off the templateRemove the view: we’ll generate that later onAdd library package reference (from command line?) to InitechDomainTpsReportsModify Index() action method:        public ActionResult Index()        {            return View(new TpsReportCoverSheet());        } Add POST action        [HttpPost]        public ActionResult Index(TpsReportCoverSheet model)        {            if (ModelState.IsValid)            {                return View("TpsReportCoverSheet", model);            }             return View(model);        } Add [Authorize] attributeAdd library package reference to InitechWebMvcAuthenticationDemonstrate it adds dependencies from NuGet as well as from Initech package repositoryWe need an implementation for the contracts… InitechAuthenticationMembershipDummy & InitechAuthenticationFormsShow the app: almost no code, we just combined some building blocks… 
  • Fun with ASP.NET MVC 3, MEF and NuGet (#comdaybe)

    1. 1. Fun with ASP.NET MVC 3,MEF and NuGet<br />Pure application LEGO<br />Maarten Balliauw<br />AZUG / VISUG<br />@maartenballiauw<br />
    2. 2. Notes (hidden)<br />So you have a team of developers… And a nice architecture to build on… How about making that architecture easy for everyone and getting developers up to speed quickly? Learn all about integrating the managed extensibility framework (MEF) and ASP.NET MVC with some NuGet sauce for creating loosely coupled, easy to use architectures that anyone can grasp.<br />So what’s this talk about?<br />Show you how you can build an app like Lego<br />Show you how you can create Lego blocks for your team<br />This is NOT a “general recommended approach”, just an idea that proved to work at one of our customers.<br />
    3. 3. Who am I?<br />Maarten Balliauw<br />Antwerp, Belgium<br /><br />Focus on web<br />ASP.NET, ASP.NET MVC, PHP, Azure, …<br />MVP ASP.NET<br /><br />@maartenballiauw<br />Me, looking intelligent with glasses<br />
    4. 4. Agenda<br />Technologies & techniques used<br />ASP.NET MVC 3<br />Managed Extensibility Framework (MEF)<br />NuGet<br />Creating application components<br />Building an application<br />Conclusion<br />Further information<br />Q&A<br />
    5. 5. ASP.NET MVC 3<br />All the new stuff:<br />Razor view engine<br />Global Action Filters<br />Unobtrusive Ajax & Client Validation<br />Better Visual Studio tooling<br />And a very interesting one for doing LEGO development:<br />Better support for Dependency Injection<br />
    6. 6. var partA =new PartA(new PartB())<br />Dependency Injection?<br />I need a “Part B” !<br />Coming up!<br />Part A<br />Me on a typicalwork day<br />
    7. 7. Container<br />Dependency Injection?<br />I need a “Part B” !<br />Let me see...<br />There you go!<br />Part A<br />Part B<br />
    8. 8. What about ASP.NET MVC 3?<br />ASP.NET MVC 3 uses DependencyResolver<br />: IDependencyResolver<br />GetService()<br />GetServices()<br />Register it on application start<br />
    9. 9. What about ASP.NET MVC 3?<br />ASP.NET MVC will / can query the IDependencyResolver for<br />Controllers<br />View engines & view pages<br />Filters<br />Model validators<br />Model metadata<br />Check Brad Wilson’s blog for examples on all of these<br /> <br />Value providers<br />Model binders<br />Controller activator<br />View page activator<br />
    10. 10. in ASP.NET MVC 3<br />Dependency Injection<br />
    11. 11. Managed ExtensibilityFramework (MEF)<br />Cool as ICE: Import, Compose, Export<br />[Import]IRule rule;<br />MEF catalog<br />HomeController<br />[Export(typeof(IRule)]<br />Let me see...<br />There you go!<br />SomeRuleImpl<br />MEF container<br />
    12. 12. MEF in ASP.NET MVC 3<br />Build an IDependencyResolver<br />based on MEF container<br />Use <br />has a built-in IDependencyResolver<br />has a “Convention” model<br />is available on NuGet<br /><br />
    13. 13. A brief NuGet introduction...<br />Package management system for .NET<br />Simplifies incorporating 3rd party libraries<br />Developer focused<br />Free, open source<br />Use packages from the official feed<br />Publish your own packages<br />Create & use your own feed<br />
    14. 14. and finding it on NuGet<br />Using MefContrib<br />
    15. 15. MefContrib.MVC3<br />Optional addition for <br />Adds some things to your application:<br />AppStart code that does the wiring<br />A CompositionDependencyResolver<br />Will check all assemblies in /bin<br />Will export everything : IController by convention<br />
    16. 16. Conventions based model<br />public class MvcApplicationRegistry : PartRegistry { public MvcApplicationRegistry() {<br /> Scan(x => {<br />x.Assembly(Assembly.GetExecutingAssembly());x.Directory(AppDomain.CurrentDomain.BaseDirectory + "bin");<br /> });<br /> Part()<br /> .ForTypesAssignableFrom<IController>()<br /> .MakeNonShared()<br /> .ExportTypeAs<IController>()<br /> .ExportType()<br /> .Imports( // ... ); }<br />}<br />
    17. 17. This all makes me think...<br />Package company components using NuGet?<br />Distribute them in a custom feed?<br />Use ASP.NET MVC 3?<br />Wire everything with MEF & MefContrib?<br />Pure application Lego!<br />Me, thinking<br />
    18. 18. application components<br />Creating<br />
    19. 19. What’s next?<br />Building it<br />MSBuild (or whatever! Nuget.exe is all that matters)<br />Hosting it<br />Create a NuGet server<br />Drop everything in a folder<br />Use a NaaS solution:<br />Using it<br />Reference the feed<br />Download & install components needed<br />Assemble using MEF (or another IoC)<br />Install-Package NuGet.Server<br />
    20. 20. A quick commercial plug<br />Create your own NuGet feed<br />Packages from official feed<br />Uploaded/pushed packages<br />No need to setup & maintain your own NuGet Server<br />Free!<br />
    21. 21. a private NuGet feed<br />Creating it the lazy way<br />
    22. 22. Let’s see if we can build this...<br />Wiredwith MEF<br />Packagedas .nupkg<br />
    23. 23. Cover Sheet Generator<br />Building an application<br />
    24. 24. Conclusion<br />You can build an app like a Lego set<br />Requires “bricks” (NuGet packages)<br />Requires “glue” (MEF / MefContrib / IoC)<br />Requires you to think in terms of components<br />Structure is key!<br />Not a best-practice architecture<br />Just something we toyed with on a project<br />Proved to work (for the customer)<br />
    25. 25. Further information<br />On the Internet:<br /><br /><br /><br />
    26. 26. Register today and save $500 before August 1st<br />Save the date: watch live stream, join local events by MSDN Belux<br />Win a ticket today at Communiday Day!<br /><ul><li>Take a picture wearing the BUILD t-shirt.
    27. 27. Tweet or blog the picture, link to, use tag #bldwin
    28. 28. Wear the t-shirt and be there for the closing prize draw</li></ul><br />
    29. 29. Thank you for joiNING<br /><br />@maartenballiauw<br />Me, having a question<br />