KEMBAR78
Fun with ASP.NET MVC 3, MEF and NuGet | PPTX
OPN07Fun with ASP.NET MVC 3, MEF and NuGetMaarten BalliauwTechnical ConsultantRealDolmen@maartenballiauw
Notes (hidden)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.So what’s this talk about?Show you how you can build an app like LegoShow you how you can create Lego blocks for your teamThis is NOT a “general recommended approach”, just an idea that proved to work at one of our customers.
Who am I?Maarten BalliauwAntwerp, Belgiumwww.realdolmen.comFocus on webASP.NET, ASP.NET MVC, PHP, Azure, …MVP ASP.NEThttp://blog.maartenballiauw.be@maartenballiauwMe, looking intelligent with glasses
AgendaTechnologies & techniques usedASP.NET MVC 3Managed Extensibility Framework (MEF)NuGetCreating application componentsBuilding an applicationConclusionFurther informationQ&A
ASP.NET MVC 3All the new stuff:Razor view engineGlobal Action FiltersUnobtrusive Ajax & Client ValidationBetter Visual Studio toolingAnd a very interesting one for doing Lego development:Better support for Dependency Injection
var partA =new PartA(new PartB())Sidenote: Dependency Injection?I need a “Part B” !Coming up!Part AMe, doing actual software development
ContainerSidenote: Dependency Injection?I need a “Part B” !Let me see...There you go!Part APart B
How does this fit into ASP.NET MVC 3?ASP.NET MVC 3 uses DependencyResolver: IDependencyResolverGetService()GetServices()Register it on application start
How does this fit in ASP.NET MVC 3?ASP.NET MVC will / can query the IDependencyResolver forControllersView engines & view pagesFiltersModel validatorsModel metadataCheck Brad Wilson’s blog for examples on all of thesehttp://bradwilson.typepad.com/blog/2010/07/service-location-pt1-introduction.html Value providersModel bindersController activatorView page activator
Dependency Injection in ASP.NET MVC 3demo
Managed Extensibility Framework (MEF)Cool as ICE: Import, Compose, Export[Import]Ilogger logger;MEF catalogHomeController[Export(typeof(Ilogger)]Let me see...There you go!ConsoleLoggerMEF container
Options for MEF in ASP.NET MVC 3Build an IDependencyResolverbased on MEF containerUse MefContribhas a built-in IDependencyResolverhas a “Convention” modelis available on NuGetmefcontrib.codeplex.com
A brief NuGet introduction...Package management system for .NETSimplifies incorporating 3rd party librariesDeveloper focusedFree, open sourceUse packages from the official feedPublish your own packagesCreate & use your own feed
Using MefContribAnd finding it. On NuGet.demo
MefContrib.MVC3Optional addition for MefContribAdds some things to your application:AppStart code that does the wiringA CompositionDependencyResolverWill check all assemblies in /binWill export everything : IController by convention
Conventions in MefContrib-MVC3public class MvcApplicationRegistry : PartRegistry {  public MvcApplicationRegistry() {Scan(x => {x.Assembly(Assembly.GetExecutingAssembly());x.Directory(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin"));  });   Part()     .ForTypesAssignableFrom<IController>()   .MakeNonShared()   .ExportTypeAs<IController>()   .ExportType()   .Imports(        // ...       );  }}
This all makes me think...Package company components using NuGet?Distribute them in a custom feed?Use ASP.NET MVC 3?Wire everything with MEF & MefContrib?Pure application Lego!Me, actually thinking
Creating application componentsInitech Default Themedemo
What’s next?Building itMSBuild (or whatever! Nuget.exe is all that matters)Hosting itCreate a NuGet serverOr drop everything in a folderUsing itReference the feedDownload & install components neededAssemble using MEF (or another IoC)Install-Package NuGet.Server
Let’s see if we can build this...Wiredwith MEFPackagedas .nupkg
Building an applicationTPS ReportsCover Sheet Generatordemo
ConclusionYou can build an app like a Lego setRequires “bricks” (NuGet packages)Requires “glue” (MEF / MefContrib / other IoC)Requires you to think in terms of componentsStructure is key!Not a best-practice architectureJust something we toyed with on a projectProved to work (for the customer)
Further informationFor time travelers:FRM06 – Deconstructing Orchard – Bradley Millington – Lagoon L (Tuesday)FRM13 – Scaffolding – Steve Sanderson – Breakers H (Wednesday)Upcoming:FRM09 – NuGetIn Depth – Scott Hanselman & Phil Haack –Lagoon H (now)On the Internet:www.nuget.orgmefcontrib.codeplex.com
Thank you for joining     & filling out the evals!Q&Ahttp://blog.maartenballiauw.be@maartenballiauwMe, having a question
OPN07Fun with ASP.NET MVC 3, MEF and NuGetMaarten BalliauwTechnical ConsultantRealDolmen@maartenballiauw

Fun with ASP.NET MVC 3, MEF and NuGet

  • 2.
    OPN07Fun with ASP.NETMVC 3, MEF and NuGetMaarten BalliauwTechnical ConsultantRealDolmen@maartenballiauw
  • 3.
    Notes (hidden)So youhave 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.So what’s this talk about?Show you how you can build an app like LegoShow you how you can create Lego blocks for your teamThis is NOT a “general recommended approach”, just an idea that proved to work at one of our customers.
  • 4.
    Who am I?MaartenBalliauwAntwerp, Belgiumwww.realdolmen.comFocus on webASP.NET, ASP.NET MVC, PHP, Azure, …MVP ASP.NEThttp://blog.maartenballiauw.be@maartenballiauwMe, looking intelligent with glasses
  • 5.
    AgendaTechnologies & techniquesusedASP.NET MVC 3Managed Extensibility Framework (MEF)NuGetCreating application componentsBuilding an applicationConclusionFurther informationQ&A
  • 6.
    ASP.NET MVC 3Allthe new stuff:Razor view engineGlobal Action FiltersUnobtrusive Ajax & Client ValidationBetter Visual Studio toolingAnd a very interesting one for doing Lego development:Better support for Dependency Injection
  • 7.
    var partA =newPartA(new PartB())Sidenote: Dependency Injection?I need a “Part B” !Coming up!Part AMe, doing actual software development
  • 8.
    ContainerSidenote: Dependency Injection?Ineed a “Part B” !Let me see...There you go!Part APart B
  • 9.
    How does thisfit into ASP.NET MVC 3?ASP.NET MVC 3 uses DependencyResolver: IDependencyResolverGetService()GetServices()Register it on application start
  • 10.
    How does thisfit in ASP.NET MVC 3?ASP.NET MVC will / can query the IDependencyResolver forControllersView engines & view pagesFiltersModel validatorsModel metadataCheck Brad Wilson’s blog for examples on all of thesehttp://bradwilson.typepad.com/blog/2010/07/service-location-pt1-introduction.html Value providersModel bindersController activatorView page activator
  • 11.
    Dependency Injection inASP.NET MVC 3demo
  • 12.
    Managed Extensibility Framework(MEF)Cool as ICE: Import, Compose, Export[Import]Ilogger logger;MEF catalogHomeController[Export(typeof(Ilogger)]Let me see...There you go!ConsoleLoggerMEF container
  • 13.
    Options for MEFin ASP.NET MVC 3Build an IDependencyResolverbased on MEF containerUse MefContribhas a built-in IDependencyResolverhas a “Convention” modelis available on NuGetmefcontrib.codeplex.com
  • 14.
    A brief NuGetintroduction...Package management system for .NETSimplifies incorporating 3rd party librariesDeveloper focusedFree, open sourceUse packages from the official feedPublish your own packagesCreate & use your own feed
  • 15.
    Using MefContribAnd findingit. On NuGet.demo
  • 16.
    MefContrib.MVC3Optional addition forMefContribAdds some things to your application:AppStart code that does the wiringA CompositionDependencyResolverWill check all assemblies in /binWill export everything : IController by convention
  • 17.
    Conventions in MefContrib-MVC3publicclass MvcApplicationRegistry : PartRegistry { public MvcApplicationRegistry() {Scan(x => {x.Assembly(Assembly.GetExecutingAssembly());x.Directory(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin")); }); Part() .ForTypesAssignableFrom<IController>() .MakeNonShared() .ExportTypeAs<IController>() .ExportType() .Imports( // ... ); }}
  • 18.
    This all makesme think...Package company components using NuGet?Distribute them in a custom feed?Use ASP.NET MVC 3?Wire everything with MEF & MefContrib?Pure application Lego!Me, actually thinking
  • 19.
  • 20.
    What’s next?Building itMSBuild(or whatever! Nuget.exe is all that matters)Hosting itCreate a NuGet serverOr drop everything in a folderUsing itReference the feedDownload & install components neededAssemble using MEF (or another IoC)Install-Package NuGet.Server
  • 21.
    Let’s see ifwe can build this...Wiredwith MEFPackagedas .nupkg
  • 22.
    Building an applicationTPSReportsCover Sheet Generatordemo
  • 23.
    ConclusionYou can buildan app like a Lego setRequires “bricks” (NuGet packages)Requires “glue” (MEF / MefContrib / other IoC)Requires you to think in terms of componentsStructure is key!Not a best-practice architectureJust something we toyed with on a projectProved to work (for the customer)
  • 24.
    Further informationFor timetravelers:FRM06 – Deconstructing Orchard – Bradley Millington – Lagoon L (Tuesday)FRM13 – Scaffolding – Steve Sanderson – Breakers H (Wednesday)Upcoming:FRM09 – NuGetIn Depth – Scott Hanselman & Phil Haack –Lagoon H (now)On the Internet:www.nuget.orgmefcontrib.codeplex.com
  • 25.
    Thank you forjoining & filling out the evals!Q&Ahttp://blog.maartenballiauw.be@maartenballiauwMe, having a question
  • 26.
    OPN07Fun with ASP.NETMVC 3, MEF and NuGetMaarten BalliauwTechnical ConsultantRealDolmen@maartenballiauw
  • 27.
    © 2011 MicrosoftCorporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

Editor's Notes

  • #5 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 = &quot;Welcome, this text has been injected!&quot;;                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&lt;object&gt; GetServices(Type serviceType)        {            return new object[] { GetService(serviceType) };        }    } Register dependencyresolver in App_Start:DependencyResolver.SetResolver(new SimpleDependencyResolver());
  • #6 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 &quot;Hello from HelloWorldService!&quot;;        }    } 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
  • #7 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!
  • #8 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(&quot;TpsReportCoverSheet&quot;, 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 &amp; InitechAuthenticationFormsShow the app: almost no code, we just combined some building blocks…