-
-
Save ahjohannessen/789885 to your computer and use it in GitHub Desktop.
This file contains 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
// In a StructureMap registry somewhere (for us, it's in CoreRegistry.cs) | |
For<IObjectConverter>().Use<DovetailObjectConverter>(); | |
// In another file, we set up some of our conversions and conversion families | |
public class DovetailObjectConverter : ServiceEnabledObjectConverter | |
{ | |
public DovetailObjectConverter(IServiceLocator locator) | |
: base(locator) | |
{ | |
// We use UTC for all DateTimes. When they come in from the user, | |
// we immediately convert them from user local timezone to UTC | |
// This is to prevent brain-bending timezone conversion math | |
// from being scattered throughout our code base. | |
RegisterConverter<DateTime, ITimeZoneContext>((context, text) => | |
{ | |
var localDate = (DateTime)Convert.ChangeType(text, typeof(DateTime)); | |
return localDate.ToUniversalTime(context.GetTimeZone()); | |
}); | |
// This is what Dru was asking about on the list. When an entity is | |
// is required, the value in the HTTP Request is a string that contains | |
// the GUID identifier of the entity (the entity type is already known | |
// or inferred from elsewhere). The code for the DomainEntityConverterFamily | |
// is located below. | |
RegisterConverterFamily<DomainEntityConverterFamily>(); | |
// This is a one-off converter for TimeSpan objects represented in string form | |
// coming up from the browser. | |
RegisterConverter<TimeSpan>(x => | |
{ | |
var returnValue = new TimeSpan(); | |
return TimeSpan.TryParse(x, out returnValue) ? returnValue : TimeSpan.Zero; | |
}); | |
} | |
} | |
// This is how we convert a string GUID into a domain entity for model binding | |
// in an action: | |
public class DomainEntityConverterFamily : IObjectConverterFamily | |
{ | |
private readonly IRepository _repository; | |
public DomainEntityConverterFamily(IRepository repository) | |
{ | |
_repository = repository; | |
} | |
// Matches any type deriving from DomainEntity | |
// CanBeCastTo<> is an extension method in FubuCore as well | |
public bool Matches(Type type, IObjectConverter converter) | |
{ | |
return type.CanBeCastTo<DomainEntity>(); | |
} | |
// In this case we find the correct object by looking it up by Id | |
// from our repository | |
public Func<string, object> CreateConverter(Type type, Cache<Type, Func<string, object>> converters) | |
{ | |
return text => | |
{ | |
var guid = new Guid(text); | |
return _repository.Find(type, guid); | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment