Skip to content

Instantly share code, notes, and snippets.

@taylonr
Forked from beolson/gist:2778777
Created May 24, 2012 02:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save taylonr/2779125 to your computer and use it in GitHub Desktop.
Save taylonr/2779125 to your computer and use it in GitHub Desktop.
Playing around with validation
// make sure to add autofac to the project
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Autofac;
using Autofac.Configuration;
namespace ValidationTest
{
class Program
{
static void Main(string[] args)
{
var builder = new ContainerBuilder();
builder.RegisterType<UserValidator>().As<IValidate<UserModel>>();
builder.RegisterType<AccountValidator>().As<IValidate<AccountModel>>();
builder.RegisterType<db>().As<Idb>();
var container = builder.Build();
var validator = container.Resolve<IValidate<UserModel>>();
Console.WriteLine(validator.Validate(new UserModel() { Id = 1, Name = "test" }));
var validator2 = container.Resolve<IValidate<AccountModel>>();
Console.WriteLine(validator2.Validate(new AccountModel() { Id = 1, Name = "test" }));
Console.ReadLine();
}
}
interface IValidate<T>
{
bool Validate(T model);
}
class UserModel
{
public int Id { get; set; }
public String Name { get; set; }
}
class UserValidator : IValidate<UserModel>
{
Idb _db;
public UserValidator(Idb db)
{
_db = db;
}
public bool Validate(UserModel model)
{
return _db.ValidateUser(model.Id);
}
}
class AccountModel
{
public int Id { get; set; }
public String Name { get; set; }
}
class AccountValidator : IValidate<AccountModel>
{
Idb _db;
public AccountValidator(Idb db)
{
_db = db;
}
public bool Validate(AccountModel model)
{
return _db.ValidateAccount(model.Id);
}
}
interface Idb
{
bool ValidateUser(int Id);
bool ValidateAccount(int Id);
}
class db : Idb
{
public bool ValidateUser(int Id)
{
return true;
}
public bool ValidateAccount(int Id)
{
return false;
}
}
}
@taylonr
Copy link
Author

taylonr commented May 24, 2012

One issue I see with this, is for the routine stuff (validating an account or user) 95% of the data is getting the user model, which means we'd need something more like UserValidator : IValidator but then you run into the problem of UserValidator and AccountValidator needing to work on an int.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment