Showing posts with label StructureMap. Show all posts
Showing posts with label StructureMap. Show all posts

Wednesday, May 09, 2012

Testing for StructureMap Default Instances

Have you ever received the good ole “No Default Instance defined for PluginFamily”? error while using StructureMap? I thought I’d share a quick test you can write to catch this error before you deploy the bug. This test is particularly useful when you mostly depend on the default conventions.

In the example provided, I’ll be verifying that I can get a default instance of all my controllers. So I’ve setup 5 controllers and 2 have constructors with some type of dependency.

Something like this:

So now I can setup my test, which looks like this:


If you’re not familiar with TestCaseSource, I blogged about it a few weeks ago on the Headspring blog, so you can read about it there. The test queries the assembly containing HomeController for all types that are a subclass of Controller and are not abstract. After it gets the type, it tries to get an instance of it from the object factory. If it fails, the test fails with what specifically it couldn’t return and which controller couldn’t be instantiated.

Here’s what the test looks like when they all pass:

CropperCapture[7]

Here’s what the tests look like when the two with dependencies fails:

CropperCapture[8]

Here’s a detailed view of one of the error messages:

CropperCapture[9]

Notice it says IAuthenticationService and it failed on the AccountController, so we know exactly where to start looking. The only other thing I probably need to mention is the TestBase, which contains the StructureMap initialization. You could simply register your StructureMap registry file there. Here’s what the example looks like:

If anyone has any suggestions on how to improve the test or if StructureMap already has a test built-in that I’m not familiar with, please share.

kick it on DotNetKicks.com

Friday, April 15, 2011

ASP.NET MVC 3 Sample Project Launched




Okay, after popular demand of I think 0 people, I’ve published my old demo MVC 1 project as an MVC 3 project. If you haven’t read any of the posts on the last demo project, check out this post. This project completely separates UI & C# code, so you only have 2 projects (Core & UI…not counting the Unit Tests project).

Basically, all I did was create a new MVC 3 project using Razor with Microsoft’s default template and deleted everything except the following:

  • Views folder
  • Root Default.aspx
  • global.asax (I did delete the global.asax.cs)
  • both web.configs

I referenced my Core, setup my views that match my Core project, and inherited from my global.cs in the global.asax. That was it!

You can download it via zip here: http://code.google.com/p/derans/downloads/list (the file is called DemoPhotographySite_v3.zip)

I feel like this project will act as a great stepping stone to understanding the Code Camp server, which is much more complex.

The sample project was built with the following tools:

If you downloaded the old one, you’ll notice that I removed the following 3rd parties:

The primary reason I removed these three parties is because MVC 3 and Razor are good enough so you don’t need the 3rd party tools.

The best practices I mentioned above come straight from experience and the following people/resources:

You can see the exact same Core code in use at sweetandhappy.com. If you see any improvements that can be made or you’d just like to comment, please do so!

Also, please note that I basically am even re-posting the exact same blog post I did over a year ago with my original MVC demo project. I hope you don’t mind, but it’s late and I have to work tomorrow :)

Thanks for reading!

Shout it

kick it on DotNetKicks.com

Friday, July 16, 2010

Authenticating Against Multiple Domains with C# & StructureMap




In my place of work, we had a vendor come in and try to sell us a product that couldn’t authenticate to multiple domains. Well, we have multiple domains. Their suggestion was to consolidate into one…obviously we’re not using their product. So, in an effort to help out, I thought I’d share a method of authenticating to multiple domains.

As always, we start out with our interface…

  public interface IAuthenticationService
{
bool Validate(string username, string password);
string DefaultRedirectUrl { get; }
}

Pretty straightforward so far…I added in a DefaultRedirectUrl in case you want to route to different places depending on which domain you authenticated against.

Okay, let’s implement our interface…

    public class AuthenticationService : IAuthenticationService
{
private readonly IAuthenticationService[] _authenticators;
private string _redirecturl;

public AuthenticationService(IAuthenticationService[] authenticators)
{
_authenticators = authenticators;
}

public bool Validate(string username, string password)
{
var isValid = false;
foreach (var authenticator in _authenticators)
{
if (authenticator.Validate(username, password))
{
isValid =
true;
_redirecturl = authenticator.DefaultRedirectURL;
break;
}
}
return isValid;
}

public string DefaultRedirectUrl
{
get { return _redirecturl; }
}
}

Alrighty…so all this does is takes in an array of authentication services and then loops through them checking if they’re valid and if they are, sets isvalid to true, the redirect url, and returns.

Basically this is our master authentication service. Now, we just need one for each one of our domains. Since they’re both authenticating to AD, we’ll create a base class like this:

    public abstract class ActiveDirectoryAuthenticator : IAuthenticationService
{
private readonly ILDAP _ldap;

protected ActiveDirectoryAuthenticator(ILDAP ldap)
{
_ldap = ldap;
}

public bool Validate(string username, string password)
{
var authenticated = false;
try
{
var entry = new DirectoryEntry(_ldap.URL, username + "@" + _ldap.HostName, password);
object nativeObject = entry.NativeObject;
authenticated =
true;
}
catch (DirectoryServicesCOMException)
{
}
return authenticated;
}

public virtual string DefaultRedirectUrl
{
get { return "/"; }
}
}

So, my ILDAP interface is the same one I blogged about here. The DefaultRedirectUrl here is virtual and meant to be overridden, otherwise it’ll just redirect to the root. Okay so now we need to inherit this authenticator in our domain authentication service classes like this…

Domain #1

public class Domain1AuthenticationService : ActiveDirectoryAuthenticator
{
public Domain1AuthenticationService() : base(DependencyRegistrar.Resolve<ILDAP>(DependencyNames.Domain1LDAP))
{ }

public override string DefaultRedirectUrl
{
get
{
return "/domain1/default.aspx";
}
}
}

Domain #2

public class Domain2AuthenticationService : ActiveDirectoryAuthenticator
{
public Domain2AuthenticationService() : base(DependencyRegistrar.Resolve<ILDAP>(DependencyNames.Domain2LDAP))
{ }

public override string DefaultRedirectUrl
{
get
{
return "/domain2/default.aspx";
}
}
}

Pretty simple right? Basically we’re setting our RedirectUrl and calling our ILDAP from StructureMap. You can read more about how I implement StructureMap here. Now for the good ole StructureMap code that goes in the Registry…

ForRequestedType<ILDAP>()
.AddInstances(x =>
{
x.OfConcreteType<
LDAP>()
.WithName(
DependencyNames.Domain1LDAP)
.SetProperty(y => y.WithBaseDN(ou =>
"Users", dc => "dc1", dc => "domain", dc => "com")
.WithHost(
"dc1.domain.com"));

x.OfConcreteType<
LDAP>()
.WithName(
DependencyNames.Domain2LDAP)
.SetProperty(y => y.WithBaseDN(ou =>
"Users", dc => "dc2", dc => "domain", dc => "com")
.WithHost(
"dc2.domain.com"));
});

ForRequestedType<
IAuthenticationService>()
.TheDefault.Is.OfConcreteType<
AuthenticationService>()
.TheArrayOf<
IAuthenticationService>().Contains(x =>
{
x.OfConcreteType<
Domain1AuthenticationService>();
x.OfConcreteType<
Domain2AuthenticationService>();
});

So, how to use this in your code? Like this…

 var adService = DependencyRegistrar.Resolve<IAuthenticationService>();

if (adService.Validate(tbUsername.Text, tbPassword.Text))
{
FormsAuthentication.SetAuthCookie(tbUsername.Text, true /*persist cookie*/);

if (Request.QueryString["ReturnUrl"] == null)
Response.Redirect(adService.DefaultRedirectUrl);
else
Response.Redirect(Request.QueryString["ReturnUrl"]);
}
else
//Display Error

There it is…authenticating against multiple domains. Please let me know if you know of better ways or you see ways to improve. Thanks for reading!

Shout it

kick it on DotNetKicks.com

Monday, May 17, 2010

Testing MVC 2.0 Controllers with Moq & NUnit




So I’ve been learning more and more about how to properly test my controllers in my MVC projects and I thought I’d share. I started using Moq recently and really like the syntax. It comes more natural to me over Rhino Mocks, which is what I was using before. I also started taking advantage of the MvcContrib test helpers, which are really nice! Of course I’m using NUnit, which seems to be what just about everyone uses. On a side note, testing is one of the major reasons to switch over to MVC from web forms. If you’re not using MVC now, I highly recommend switching over. You will not be disappointed.

Alright, well I’m going to be writing the tests for the contact form I blogged about back in March. Let’s get started.

First let’s test the Index() for the ContactController.

    [TestFixture]
public class ContactControllerTests
{
[
Test]
public void Index_Should_Return_Type_Of_ContactView()
{
//Arrange
var result = new ContactController();
//Act
result.Index();
//Assert
Assert.That(result.ViewData.Model.GetType(), Is.EqualTo(typeof(ContactView)));
}
}

The general rule of thumb for a unit test is Arrange, Act, & Assert. There generally should only be one assert per test, although I don’t think it’s set in stone. I’m sure some people disagree with that statement. Anyhow, this test is simple enough. Create a new instance of the controller, call the Index() action and assert that the returned model type is of ContactView. Done.

So I start on the next test and realize I’m going to need to use the SetUp attribute because I’m going to have some recurring items. Okay, so that looks like this:

        private ContactController _contactController;
[
SetUp]
public void Setup()
{
_contactController =
new ContactController();
}

So the second test looks like this:

       [Test]
public void Send_Should_Return_ContactView_If_ModelState_Has_Error()
{
_contactController.ModelState.AddModelError(
"testerror", "test error");
_contactController.Send(
new ContactView());

Assert.That(_contactController.ViewData.Model.GetType(), Is.EqualTo(typeof(ContactView)));
}

Basically, this adds an error and calls the Send() action and finally we assert that the ContactView is passed back. Here’s where we could add another Assert that checks the IsValid on the modelstate too, but I didn’t.

Next test looks like this:

        [Test]
public void Send_Should_Call_NotificationService_If_ModelState_IsValid()
{
var notificationService = new Mock<INotificationService>();
ObjectFactory.Inject(typeof(INotificationService), notificationService.Object);
_contactController.Send(
new ContactView());

notificationService.Verify(service => service.Notify());
}

So I use Mock<> to mock the notification service and then the StructureMap ObjectFactory to inject the mock in and then call the Send() action. Finally, I assert that Notify() was called on the mock.

Next I test to make sure the Success is passed in. Looks like this:

        [Test]
public void Send_Should_Call_NotificationService_If_ModelState_IsValid_And_Return_Success()
{
_contactController.Send(
new ContactView());

Assert.That(_contactController.ViewData["Success"], Is.True);
}

Then I test if the exception is thrown and it looks like this:

        [Test]
public void Send_Should_Call_NotificationService_And_Throw_A_NotificationException_If_Send_Fails()
{
_notificationService.Setup(service => service.Notify()).Throws(
new NotificationException());
_contactController.Send(
new ContactView());

Assert.That(_contactController.ModelState.IsValid, Is.False);
}

Notice I had to put the notification service in the SetUp too. Now my setup looks like this:

        private Mock<INotificationService> _notificationService;
private ContactController _contactController;
[
SetUp]
public void Setup()
{
_notificationService =
new Mock<INotificationService>();
ObjectFactory.Inject(typeof(INotificationService), _notificationService.Object);

_contactController =
new ContactController();
}

Finally I test to make sure everything comes back okay and the ContactView is passed back too. Looks like this:

        [Test]
public void Send_Should_Return_ContactView_If_No_Errors_Occur()
{
_contactController.Send(
new ContactView());

Assert.That(_contactController.ViewData.Model.GetType(), Is.EqualTo(typeof(ContactView)));
}

I also refactored the IsValid ModelState test to this:

        [Test]
public void Send_Should_Call_NotificationService_If_ModelState_IsValid()
{
_contactController.Send(
new ContactView());

_notificationService.Verify(service => service.Notify());
}

All our tests complete and green…

image

Thanks for reading!

Download the Source Here.


Shout it

kick it on DotNetKicks.com

Thursday, April 08, 2010

Google Calendar Management with MVC & StructureMap




I recently read John Petersen’s blog entitled “Adding Google Charts to your ASP MVC Applications” and I thought it was a pretty cool read. I thought I’d do a similar one taking advantage of the Google Data API SDK.

In order to get started, you’ll need to do some setup by following the awesome instructions Google provides called Getting Started with the .NET Client Library to setup the SDK.

Let’s get to the code!

First things first, create a calendar repository interface like this:

    public interface ICalendarRepository
{
void Add(Activity activity);
void Delete(string activityId);
Activity GetById(string activityId);
Activity[] GetAll();
}

Now we just need to impelment it. I’ll go through some of this, but I think it’s pretty self-explanatory if you just read through it. I may be wrong :)

    public class GoogleCalendarRepository : ICalendarRepository
{
private const string GoogleCalendarFeed = "http://www.google.com/calendar/feeds/{0}/private/full";

private readonly string _calendarId;
private readonly CalendarService _calendarservice;
public GoogleCalendarRepository(string calendarId, string googleUsername, string googlePassword)
{
_calendarId = calendarId;
_calendarservice =
new CalendarService("Google Calendar");
_calendarservice.setUserCredentials(googleUsername, googlePassword);
}

private string GoogleCalendarFeedWithId
{
get { return string.Format(GoogleCalendarFeed, _calendarId); }
}

public void Add(Activity activity)
{
var entry = new EventEntry(activity.Title, activity.Description, activity.Location);

var eventTime = new When(activity.StartDate, activity.EndDate);
entry.Times.Add(eventTime);

var postUri = new Uri(GoogleCalendarFeedWithId);
var eventEntry = _calendarservice.Insert(postUri, entry);

activity.Id = eventEntry.EventId;
}

public void Delete(string activityId)
{
_calendarservice.Delete(getEventBy(activityId));
}

public Activity GetById(string activityId)
{
return getActivityFrom((EventEntry) getEventBy(activityId));
}

public Activity[] GetAll()
{
var query = new EventQuery();
query.Uri =
new Uri(GoogleCalendarFeedWithId);
var feed = _calendarservice.Query(query);

var activities = new List<Activity>();
foreach(var e in feed.Entries)
activities.Add(getActivityFrom((
EventEntry)e));

return activities.ToArray();
}

private static Activity getActivityFrom(EventEntry eventEntry)
{
return new Activity
{
Description = eventEntry.Content.Content,
StartDate = eventEntry.Times[
0].StartTime,
EndDate = eventEntry.Times[
0].EndTime,
Id = eventEntry.EventId,
Location = eventEntry.Locations[
0].ValueString,
Title = eventEntry.Title.Text
};
}

private AtomEntry getEventBy(string eventId)
{
try
{
var entryQuery = new EventQuery();
entryQuery.Uri =
new Uri(string.Format(GoogleCalendarFeedWithId + "/{0}", eventId));
var result = _calendarservice.Query(entryQuery);
if (result.Entries.Any())
return result.Entries[0];
}
catch {}

throw new EventNotFound();
}
}

Line 1. I inherit from my ICalendarRepository
Line 2. Open Bracket
Line 3. Constant string for the Google Uri – notice I put the {0} in there so I can plop my calendar id in its place later on.
Line 4. Line break…just kidding…I’ll just explain each group of code from here on out.

In the constructor, I take in the calendar id with a google username and google password that are authorized to modify/read the calendar. I played with a couple other authentication methods, but nothing worked as well as the good ole setUserCredentials, so I stuck with it.

NOTE: Get your Calendar Id by following these steps:

  1. Click the dropdown arrow next to your calendar name at http://www.google.com/calendar
  2. Select Calendar Settings
  3. At the bottom of the page, you’ll see “Calendar Address” look to the right of the three images shown in that section and you’ll see the Calendar ID.

After the constructor, I have a private read-only property that just formats my Google Uri with my calendar id.

Also worth noting is that I’m only referencing these namespaces: Google.GData.Calendar; Google.GData.Client; Google.GData.Extensions; in this repository. This is the ONLY place the Google namespace is mentioned in my project.

The Add method is simple enough. It accepts an activity, creates an EventEntry, and uses the calendar service that’s initialized in our constructor to insert the event and then it sets the activity.Id to the new id created.

The Delete method is even easier. It calls the Delete method on the calendar service and the getEventBy() private method to get the event via an EventQuery. I extracted that code out because I was using the code in my Delete and in the next method, GetById.

In GetById, I call another private method called getActivityFrom(), which does the same thing that AutoMapper would have done, but this was easier for this sample. I also needed to extract this code because I was doing it in the GetById & GetAll methods. I obviously could’ve cleaned this method up and added more validation like checking if the collections are null before just referencing them, but this is an example :)

That’s it for the repository!

The EventNotFound exception thrown in the getEventBy method looks like this if you’re wondering:

    public class EventNotFound : Exception
{
public override string Message
{
get { return "Event not found. Activity.Id is required."; }
}
}

The activity class looks like this:

    public class Activity
{
public string Id { get; set; }
public string Title { get; set; }
public string Location { get; set; }
public string Description { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
}

Let’s create the controller real quick as an example of how to use this repository. I’m not going to show the view code because this thing is already pretty long :)  If you think it’s necessary, feel free to comment!

    public class ActivityManagementController : Controller
{
private readonly ICalendarRepository _calendarRepository;

public ActivityManagementController(ICalendarRepository calendarRepository)
{
_calendarRepository = calendarRepository;
}

public ViewResult Add()
{
return View(new Activity());
}

[
AcceptVerbs(HttpVerbs.Post), ValidateAntiForgeryToken]
public ViewResult Add(ActivityView activity)
{
_calendarRepository.Add(
Mapper.Map(activity));

return View(activity);
}

public ViewResult View(string activityId)
{
var activity = _calendarRepository.GetById(activityId);

return View(activity);
}

public ViewResult ViewAll()
{
var activities = _calendarRepository.GetAll();

return View(activities);
}

public ViewResult Delete(string activityId)
{
_calendarRepository.Delete(activityId);

return View();
}
}

The most important thing to note here is the controller constructor. What it allows us to do is inject whatever repository we want into the controller via StructureMap. So, let’s take a look at the StructureMap configuration.

    public class DependencyRegistry : Registry
{
protected override void configure()
{
Scan(x =>
{
x.TheCallingAssembly();
x.WithDefaultConventions();
});

ForRequestedType<
ICalendarRepository>()
.TheDefault.Is.OfConcreteType<
GoogleCalendarRepository>()
.WithCtorArg(
"calendarId").EqualToAppSetting("calendarId")
.WithCtorArg(
"googleUsername").EqualToAppSetting("googleUsername")
.WithCtorArg(
"googlePassword").EqualToAppSetting("googlePassword");
}
}

That’s all you’ll need to get this thing up and running. If you get the “No parameterless constructor…” error, then you need to look at rolling out your own controller factory that leverages StructureMap. You can see an example in my demo MVC app.

Well, I guess that’s it for now. Obviously there are more items we could include in our Activit object that Google has in their’s, but I mainly wanted to show how to get it setup. Anyhow, I hope you enjoyed it and please feel free to comment.

Thanks for reading!


Shout it

kick it on DotNetKicks.com

Sunday, February 28, 2010

Authentication with Active Directory, ASP.NET MVC, & fluentHtml




I figure since people are starting to really look into MVC and are realizing that it’s going to be around for a while, they’re going to need some decent samples when researching how to do things. I’m hoping this particular post will possibly be one of those examples. I had the same thought when I wrote the Security Questions with ASP.NET MVC & fluentHtml post.

Let’s get started with the view model class for the sign in page. By the way, if you’re not familiar with the way I setup my MVC projects, see this post.

public class SignInView
{
[
ValidateNonEmpty("Username is required.")]
public string Username { get; set; }
[
ValidateNonEmpty("Password is required.")]
public string Password { get; set; }
}

Really simple. The ValidateNonEmpty is an attribute from the Castle project and I’m passing in the error message I want displayed if invalid.

Okay, so let’s go ahead and pass in this view model to our actual view from the AuthenticationController. This will look like this:

public ActionResult Index()
{
return View(new SignInView());
}

Now we’ll create our actual view (html):

<%=Html.DivValidationSummary("All fields are required.") %>
<form action="/authentication/index" method="post">
<
fieldset>
<
legend>Sign In</legend>
<
p><%=this.TextBox(f => f.Username).Label("Username: ")%></p>
<
p><%=this.Password(f => f.Password).Label("Password: ")%></p>
<%=Html.AntiForgeryToken() %>
<%=Html.SubmitButton("Sign In", cssclass=>"sb", accesskey=>"S") %>
</
fieldset>
</
form>

This is our basic html setup with fluentHtml added to it. If you need a tutorial on fluentHtml, here’s a post on it. Basically, I’m using my htmlHelper for a DivValidationSummary, I’m calling the index action on the authentication controller, then I’m setting up my textboxes with fluentHtml, using the antiforgerytoken to prevent csrf, and I’m using my submit button that I blogged about before this post.

Now let’s look at the action that’s being called by the form above.

[AcceptVerbs(HttpVerbs.Post), ValidateModel(typeof(SignInView)), ValidateAntiForgeryToken]
public ViewResult Index(SignInView form)
{
if (!ModelState.IsValid)
return View("index", form);

IUser user = DependencyRegistrar.With<string, IUser>(form.Username);
bool passwordMatches = _authenticationService.PasswordMatches(user, form.Password);

if (passwordMatches)
{
//Sign In – Write Cookie & Redirect most likely through a UserSession
}

ModelState.AddModelError(
"SignIn", "Invalid credentials");
return View("index", form);
}

Okay, so you can see I’m accepting only post, I’m validating the model, and I’m validating the token. I’m also accepting my SignInView model. If the model state is not valid I return the model back to the view. Otherwise, I get an instance of user with my username and then I call my authenticationService. If passwordMatches, sign in and return, otherwise add an error and return.

So let’s look at my IUser real quick. It’s really simple:

public interface IUser
{
string Username { get; set; }
}

Think my AuthenticationService is much more difficult? Of course not!

public interface IAuthenticationService
{
bool PasswordMatches(IUser user, string password);
}

By the way, I’m accepting an instance of IAuthenticationService in the constructor of the controller like so:

public AuthenticationController(IAuthenticationService authenticationService)
{
_authenticationService = authenticationService;
}

I’m using StructureMap to know what to pass in to the constructor. Okay, so my AuthenticationService implementation looks like this:

public class AuthenticationService : IAuthenticationService
{
private readonly IActiveDirectorySettings _adSettings;

public AuthenticationService(IActiveDirectorySettings activeDirectorySettings)
{
_adSettings = activeDirectorySettings;
}

public bool PasswordMatches(IUser user, string password)
{
var authenticated = false;
var domainAndUsername = _adSettings.DomainName + "\\" + user.Username;
var entry = new DirectoryEntry("LDAP://" + _adSettings.LdapPath, domainAndUsername, password);

try
{
var bindToNativeObjectToForceAuthentication = entry.NativeObject;
authenticated =
true;
}
catch (COMException)
{
}

return authenticated;
}
}

Now my IActiveDirectoryCredentials looks like this:

public interface IActiveDirectorySettings
{
string DomainName { get; }
string LdapPath { get; }
}

That’s basically it. There’s not a whole lot to an authentication process, but thought I’d share anyhow.

Thanks for reading!


Shout it

kick it on DotNetKicks.com

Friday, January 15, 2010

Validator Injection with C# and StructureMap




I recently had a need to setup validation rules for a registration system. I thought I would share how I was able to create a generic Validator with rules to pass through. Let’s get started.

So I had a rule that an email address couldn’t already exist in the database. So first I needed to define what a rule would look like and this is what I came up with:

    public interface IValidationRule<T>
{
bool IsValid(T model);
}

Here is the implementation:

 public class EmailAddressDoesNotExistRule : IValidationRule
{
private readonly string _connstring;

public EmailAddressDoesNotExistRule(string connstring)
{
_connstring = connstring;
}

public bool IsValid(User user)
{
using (var db = new DataContext(_connstring))
return !db.EmailAddress.Any(x => x.EmailAddress == user.EmailAddress);
}
}

So now do I pass in an IValidationRule to where I want to validate? No. Do I create an array of IValidationRule in the constructor of what I want to validate? Nope. Do I create an IValidator and pass that in? YEP! Let’s take a look at the IValidator and the implementation.


Here is the interface:

public interface IValidator<T>
{
bool IsValid(T model);
}

Here is the implementation:

public class Validator<TModel, TRule> : IValidator<TModel>
where TRule : IValidationRule<TModel>
{
private readonly TRule[] _validationRules;

public Validator(TRule[] validationRules)
{
_validationRules = validationRules;
}

public bool IsValid(TModel model)
{
var isValid = false;
foreach (TRule rule in _validationRules)
{
if (rule.IsValid(model))
isValid =
true;
else
{
isValid =
false;
break;
}
}

return isValid;
}
}

If you’re not familiar with .NET generics, you might want to do some research about them. They’re awesome!


Okay, so how do we tie it into our service? Well, we’re going to inject it into the constructor like so:

        private readonly IUserValidator _userValidator;

public UserRegistrationService(IUserValidator userValidator)
{
_userValidator = userValidator;
}

I’m sure you’re asking…where did the IUserValidator come from? Well, IUserValidator looks like this:

    public interface IUserValidator : IValidator<User>
{
}

Very simple and basically I only do this to make my code more readable. So the implementation of this IUserValidator looks like this:

public class UserValidator : Validator<User, IValidationRule>, IUserValidator
{
public UserValidator(IValidationRule[] validationRules)
:
base(validationRules)
{
}
}

So now back in our UserRegistrationService, we have a method that just calls the IsValid on the validator like this:

        public void CreateNewRegistration(User user)
{
if (_userValidator.IsValid(user))
//CreateAccountFor(user);
else
//throw new InvalidUserException();
}

Okay, so now for my FAVORITE part of this method for validating…the StructureMap code.


In my DependencyRegistry configure(), I added this code:

            ForRequestedType<IUserValidator>()
.TheDefault.Is.OfConcreteType<UserValidator>()
.TheArrayOf<IValidationRule>().Contains(x =>
{
x.OfConcreteType<EmailAddressDoesNotExistRule>()
.WithCtorArg(
"connstring")
.EqualTo(WebConfig.TeamsConnectionString);

//add more here like the line above
});

So as you add validation rules, you simply add them to your configure() and they’re lined up and ready to go! I’ve also seen this method used with formatting rules. I think it’s pretty awesome!


NOTE: If you have a lot of DB calls for validation, you may want to include some type of loader in the Validator and just pass in the items so you’re not making a ton of DB calls.


Let me know what you think and thanks for reading!


Shout it

kick it on DotNetKicks.com

Related Posts Plugin for WordPress, Blogger...