Fluent+AutoFAC模式在ASP.NET MVC中的應用場景:
話說應該先介紹一些IoC或者Dependency Injection之類的東西,但我確實是才學這些不多久,雖然接觸ASP.NET許久。
通過添加引用autofac,完成autofac的基本註冊,等於完成autofac的asp.net MVC集成。Web.config中添加:
<httpModules> <add name="ContainerDisposal" type="Autofac.Integration.Web.ContainerDisposalModule,Autofac.Integration.Web"/> <add name="PropertyInjection" type ="Autofac.Integration.Web.Forms.PropertyInjectionModule,Autofac.Integration.Web"/> </httpModules>
例如在DependencyRegistrar.cs中
builder.RegisterType<GeoCountryLookup>().As<IGeoCountryLookup>().InstancePerHttpRequest(); builder.RegisterType<CountryService>().As<ICountryService>().InstancePerHttpRequest();
在Global.asax中register Person。
Validation部分:
先添加引用:
由於使用了Ioc,我們看到在Controller中也可以使用帶有參數的方式了:
ModelValidatorProviders.Providers.Add( new FluentValidationModelValidatorProvider(new NopValidatorFactory()));
通過在Model類對象上使用Validator Attribute實現自動的驗證
using FluentValidation.Attributes;
[Validator(typeof(NewsItemValidator))] public class NewsItemModel : BaseNopEntityModel { [NopResourceDisplayName("Admin.ContentManagement.News.NewsItems.Fields.Language")] public int LanguageId { get; set; }
在Admin的Model中以及front Web的Model中
[Validator(typeof(NewsItemValidator))] public class NewsItemModel : BaseNopEntityModel { public NewsItemModel() { Tags = new List<string>(); Comments = new List<NewsCommentModel>(); AddNewComment = new AddNewsCommentModel(); }
。。 。。。 。。。
更多詳細資料,請參考http://code.google.com/p/autofac/