MultipleGenericBindingGenerator for Ninject.Extensions.Conventions

by Rok Bermež 10. January 2011 17:55
Ninject.Extensions.Conventions provides convention based binding for Ninject modeled after the StructureMap 2.5 AssemblyScanner by Jeremy Miller. When StructureMap users can use something like: Scan(scanner => { scanner.AssembliesFromApplicationBaseDirectory(assembly => assembly.FullName.StartsWith("Ntk.Infrastructure.")); scanner.ConnectImplementationsToTypesClosing(typeof (IMessageHandler <,>)); scanner.ConnectImplementationsToTypesClosing(typeof (IMessageHandler <>)); }); Ninject.Extensions.Conventions using GenericBindingGenerator can not: kernel.Scan(scanner => { scanner.FromAssembliesMatching( "Ntk.Infrastructure.*.dll" ); scanner.BindWith(new GenericBindingGenerator(typeof(IMessageHandler<>))); scanner.BindWith(new GenericBindingGenerator(typeof(IMessageHandler<,>))); scanner.InTransientScope(); }); So slightly modified version of GenericBindingGenerator called MultipleGenericBindingGenerator comes to the rescue: kernel.Scan(scanner => { scanner.FromAssembliesMatching("Ntk.Infrastructure.*.dll"); scanner.BindWith(new MultipleGenericBindingGenerator(typeof(IMessageHandler<>),typeof(IMessageHandler<,>))); scanner.InTransientScope(); }); If anyone needs anything like this, here is the code: using System; using System.Collections.Generic; using System.Linq; using System.Web; using Ninject; using Ninject.Activation; using Ninject.Extensions.Conventions; namespace TestProj{ public class MultipleGenericBindingGenerator : IBindingGenerator { private static readonly Type TypeOfObject = typeof (object); private readonly Type[] _contractTypes; /// <summary> /// Initializes a new instance of the <see cref="MultipleGenericBindingGenerator"/> class. /// </summary> /// <param name="contractTypes">Types of the contract.</param> public MultipleGenericBindingGenerator(params Type[] contractTypes) { foreach (var type in contractTypes) { if (!(type.IsGenericType || type.ContainsGenericParameters)) { throw new ArgumentException(String.Format("The contract must be an open generic type ({0}).",type.Name), "contractTypes"); } } _contractTypes = contractTypes; } #region Implementation of IBindingGenerator /// <summary> /// Processes the specified type creating kernel bindings. /// </summary> /// <param name="type">The type to process.</param> /// <param name="scopeCallback">the scope callback.</param> /// <param name="kernel">The kernel to configure.</param> public void Process( Type type, Func<IContext, object> scopeCallback, IKernel kernel ) { Type interfaceType = ResolveClosingInterface( type ); if ( interfaceType != null ) { kernel.Bind( interfaceType ).To( type ).InScope( scopeCallback ); } } #endregion /// <summary> /// Resolves the closing interface. /// </summary> /// <param name="targetType">Type of the target.</param> /// <returns></returns> public Type ResolveClosingInterface( Type targetType ) { if ( targetType.IsInterface || targetType.IsAbstract ) { return null; } do { Type[] interfaces = targetType.GetInterfaces(); foreach ( Type @interface in interfaces ) { if ( !@interface.IsGenericType ) { continue; } if (_contractTypes.Contains(@interface.GetGenericTypeDefinition())) { return @interface; } } targetType = targetType.BaseType; } while ( targetType != TypeOfObject ); return null; } } }

Tags:

.Net | c# | ASP.NET | mvc | Web

T4MVC templates for strongly typed ASP.MVC

by Rok Bermež 10. January 2011 12:19
T4 templates for strongly typed ASP.MVC   MVC is a software pattern, that has been first introduced 1979 by Norwegian scientist Trygve Reenskaug.  The idea was to decouple the tight knot between views and models, to have a much more control over the software. For example, very known ASP.NET 2.0 technology had the implementation of views, but controllers and models were combined in the code behind, which has the impact on the testing and other features, which is needed to build a easy proficient sustainable web solution. Year ago Microsoft has launched a framework ASP.NET MVC for supporting software pattern and add additional value with different view engines , such as Razor, to eliminate this requirement. Since then, developers are having  few consideration about choosing between ASP.NET WebForms and ASP.NET MVC, but that is topic for another blog post. MVC grew very quickly and alot of developers are using the new .NET framework to write efficient, light weight, powerfull web apps. Even though we do have a great enviroment for writing, testing, debugging  .NET apps, there is still a lack of string and mis-machted typos. Consider following example: <%:Html.ActionLink(»My link«,«Indeks«,«Home«) %> This is a link to the Home controller, with a method Indeks. But wait, there is no indeks method there. It is a typo. Since we forgot to write x, instead of ks, we got a runtime error. We have to run the site, click of the link, read the error message, ask ourself, what did we do, use the debugger, run the site, check again, go through bunch of step, just because we made a typo. This is the reason, why expert developers, such as david Ebbo, created a helper (T4 templates), that goes through the code and created a strongly typed strings for controllers, views, even a content. Fixed upper example: <%:Html.ActionLink(»My link«, MVC.Home.Index)%> Its so easy. No more runtime checking, no repro bugs, even intellisense helps us understand, which name and even parameters we will use.  You can use the following strongly typed helpers in the whole app, not only the views ( also in controllers, etc.) It is quite simple to use it: 1.       Download the zip file on the codeplex site 2.       Required watching the David Ebbo intro with examples 3.       Unzip the file 4.       Add the 2 files in the root of your MVC app (T4MVC.tt and T4MVC.setting.t4) 5.       Build it 6.       Use it J You can change the setting for t4 in the settings file to bend it to you will J Happy no-typo coding.

Tags:

.Net | c# | ASP.NET | Web | mvc

... azure looks back at you

by Rok Bermež 8. January 2011 14:22
It’s been a month since Azure SKD 1.3 has been released with a lot of new features. Let’s take a look at the ability to user Remote Desktop Connection to your roles first.In order to enable this feature we must configure our deployments to support it. The easiest way to do so is to right click on cloud service project in visual studio and choose deploys. There you can click on 'Configure Remote Desktop connections'. Here you can enable RDP connections for all roles and you must set the required security credentials. So let’s create a security certificate first. Then we set user credentials for our RDP account and set its expiration date. After that, we export the security certificate so we can upload it to the cloud (you can click on view to open it directly). We also export private key And then we upload exported file through the Windows Azure Management portal to our chosen hosted service. If we take a closer look at what our Visual Studio Wizard did, we can open ServiceDefinition.csdef and ServiceConfiguration.cscfg and see xml additions. Now we can deploy our solution anyway we like. Once the deployment is complete and our role is in 'ready' state we can download or open .rdp file through Azure Management portal. Now we can finally connect to our instance ... and azure looks back at you NOTE: Changes made to instance will NOT be persisted. This was meant for easier debugging. If you want to take full advantage of IIS configuration you will need to use ‘Full IIS’ feature, which will be covered in my next post.

Tags:

.Net | Azure | IIS | Visual Studio

MVC 3 beta on Windows Azure

by Rok Bermež 10. November 2010 10:48
This is also valid for RC release of MVC 3. When preparing a demo for my next lecture I noticed that when using MVC3 beta, everything works correctly in development fabric, but it fails when deployed to Windows Azure. Web Role is cycling between initializing / stopping and that usually mean that not all dependencies are included with the deployed project. To solve the problem just add references to the following dlls located in C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\Assemblies: System.WebPages.dll System.Web.WebPages.Razor.dll System.Web.Helpers.dll System.Web.Razor.dll WebMatrix.Data.dll Microsoft.Web.Infrastructure.dll and make sure that all of them (including System.Web.Mvc.dll (v3.0.0.0)) are marked as Copy local = true.

Tags:

.Net | ASP.NET | Azure | Web

Using MVC routing to address multi-tenant Azure applications

by Rok Bermež 11. October 2010 10:29
Currently I have a scenario where I have to have more than one site and multiple domains/subdomains in a single Windows Azure web role. For obvious reasons Windows Azure give us FQDN (like myapp.cloudapp.net) instead of IP address so we have to use CNAME to point to our instance/s. The only problem with this approach is that only domain name cannot have CNAME record. For instance www.mydomain.org is fine, but just mydomain.org is not since it needs specific IP address. For the time being this was solved by pointing it to some specific address which would redirect the user to www of that domain. That part was simple and straightforward, but now we need something inside our web role, that would detect requested domain and serve appropriate content. There are a couple of threads online that deal with the issue of addressing multi-tenant application in Windows Azure and most of them deal with url rewriting on the single domain. You can read more about it here and here. In my project I used MVC Areas to separate different sites so all I needed was MVC routing to use domain name from incoming request in its routing configuration. I found an excellent article on the subject here, but unfortunately it was written before MVC 2 introduced areas, so in order to use it lets add area support to it. First lets download the sample here, open and if needed convert solution and open DomainRoute.cs. We only need to add one line to the end of GetRouteData method: if (Defaults.Keys.Contains("area")) data.DataTokens.Add("area", Defaults["area"]); so that it looks like: if (DataTokens != null) { foreach (var token in DataTokens) { data.DataTokens.Add(token.Key, token.Value); } } if (Defaults.Keys.Contains("area")) data.DataTokens.Add("area", Defaults["area"]); } return data; }   And we are ready to register our areas as their own domains/subdomains public override void RegisterArea(AreaRegistrationContext context) { context.Routes.Add("subodomain_default", new DomainRoute( "subdomain.mydomain.si", "{controller}/{action}/{id}", new { area = AreaName, controller = "Home", action = "Index", id = UrlParameter.Optional } ) { DataTokens = new RouteValueDictionary(new { Namespaces = new string[] { "MvcWebRole1.Areas.subdomain.Controllers" } }) } ); }  I strongly suggest you pass Namspaces to every route registration so you can have multiple controllers with the same name serving different tenants. Soon Ill add a DomainRouteExtension and post it here so the usage will be even simpler.

Tags:

.Net | Azure | Web

Calendar

<<  January 2018  >>
MonTueWedThuFriSatSun
25262728293031
1234567
891011121314
15161718192021
22232425262728
2930311234

View posts in large calendar

Page List

Month List