-
-
Save taylonr/2779125 to your computer and use it in GitHub Desktop.
Playing around with validation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.