Saturday 30 April 2016

Integrating Fluent Validation in Web API using Autofac

Create New Project

Install Necessary Packages

  Install-Package Autofac
  Install-Package Autofac.WebApi2
  Install-Package FluentValidation
  Install-Package FluentValidation.WebApi
  Install-Package Microsoft.AspNet.WebApi
  Install-Package Microsoft.AspNet.WebApi.Owin
  Install-Package Microsoft.Owin.Host.SystemWeb
  Install-Package Owin
  Install-Package Newtonsoft.Json
 

Create Partial Startup Classes

Partial class is just splitting class file into two or more files, and all parts are combined when the application is compiled.

It is used in a situation

  • When working on large projects, spreading a class over separate files enables multiple programmers to work on it at the same time.
  • When working with automatically generated source, code can be added to the class without having to recreate the source file. Visual Studio uses this approach when it creates Windows Forms, Web service wrapper code, and so on. You can create code that uses these classes without having to modify the file created by Visual Studio.
  • To split a class definition, use the partial keyword modifier

While adding this class our project structure looks like.

Startup.Autofac.cs

Startup.WebApi.cs

Startup.cs

Add Infrastructure classes

Now our Project structure looks like

AutofacValidatorFactory.cs

AutofacWebModule.cs

ValidateFilterAttribute.cs

Add Modal Validation and Controller

Now our Project structure looks like

Controller

Model and Model Validation

Finally test our code




Thanks,


Download Code

1 comment:

  1. Hi... If you add a dependency in the validator constructor (PersonValidator), it throws a exception:

    An exception of type 'Autofac.Core.DependencyResolutionException' occurred in Autofac.dll but was not handled in user code

    Additional information: None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'FluentAutofacValidationAPI.Models.PersonValidator' can be invoked with the available services and parameters:

    Cannot resolve parameter 'FluentAutofacValidationAPI.Infrastructure.IStudentService service' of constructor 'Void .ctor(FluentAutofacValidationAPI.Infrastructure.IStudentService)'.

    ReplyDelete