Robert,
Thank you for such a quick response. Registering the class maps in the
static constructor works great for most cases. I have one situation
where I am specifying a custom HiLoIdGenerator (Ported from NoRM) that
gets built up by the UnityContainer. In that case I can't use the
static constructor to wire it up. It doesn't affect real usage but I
do have to account for the multiple class mappings when running unit
tests. I can wrap the entire block in a try /catch but I feel dirty
every time I look at it. For this scenario do you have any
suggestions? The following is an abbreviated version of my unity
container extension:
public class MongoDbContainerExtension : UnityContainerExtension
{
protected override void Initialize()
{
RegisterTypes();
try
{
MapClasses();
}
catch (ArgumentException) { }
}
private void RegisterTypes()
{
Container
.RegisterType<MongoDatabase>(new InjectionFactory((c)
=> CreateMongoDb()));
}
protected virtual MongoDatabase CreateMongoDb()
{
var settings =
ConfigurationManager.ConnectionStrings["
connectionstring.key.name"];
var server =
MongoServer.Create(settings.ConnectionString);
return server["
database.name"];
}
private void MapClasses()
{
BsonSerializer.RegisterIdGenerator(typeof(Guid), new
CombGuidGenerator());
BsonClassMap.RegisterClassMap<AuthorityLogEntryDto>(cm =>
{
cm.AutoMap();
cm.SetIdMember(cm.GetMemberMap(m => m.LogEntryId));
});
BsonClassMap.RegisterClassMap<UserDto>(cm =>
{
cm.AutoMap();
cm.SetIdMember(
cm.GetMemberMap(m => m.UserId)
.SetIdGenerator(
Container.Resolve<CollectionHiLoIdGenerator<long>>(
new ParameterOverrides {
{ "capacity", 20 },
{"collectionName", "users" }})));
});
}
}
Best regards,
Keith
On Apr 21, 6:12 am, Robert Stam <
rstam10...@gmail.com> wrote:
> The registration of class maps is deliberately designed to be
> something you do once at program startup. The reason for that is that
> you want serialization to have a stable defined behavior for the
> duration of your program run (you don't want objects serialized one
> way for awhile and then differently after that).
>
> The registration of class maps must happen:
>
> 1. Early in your program, certainly before any serialization/
> deserialization involving that class occurs
> 2. Only once
>
> A really good way to handle the "only once" requirement is to register
> the class maps from a static constructor. That way the C# language
> itself guarantees that they are only registered once. The best place
> to put the static constructor is in the class itself. In your case, I
> would recommend calling RegisterClassMap in the static constructor for
> AuthorityLogEntryDto.
>
> On Apr 21, 3:04 am, grandeconcarne <
grandeconca...@gmail.com> wrote:
>
>
>
>
>
>
>
> > Hello All,
> > I am usingUnityfor IoC and created a container extension to handle