开发者

Close open generic types with whatever is requested, by calling a lambda

I am currently using the mongodb-csharp drivers in my application.

I would like my repositories to depend on IMongoCollection<T>, and I'm trying to figure out how to configure StructureMap to let me call a lambda when it is requested. For a non-open-generic type, I have it setup like this:

For<IMongoDatabase>()
            .HybridHttpOrThreadLocalScoped()
            .Use(cx =>
                     {
                         var mongo = cx.GetInstance<IMongo>();
                         return mongo.GetDatabase("TestDB");
                     });

I would like to configure StructureMap to do something like the above with open generics, however I'm not sure how to get the type that was requested:

For(typeof (IMongoCollection<>))
            .HybridHttpOrThreadLocalScoped()
            .Use(cx =>
                     {
                         var db = cx.GetInstance<IMongoDatabase>()开发者_高级运维;
                         // How do I figure out what to close the generic with?
                         return db.GetCollection<T>();
                     });

Is this possible with StructureMap? I feel like I'm missing something here...


Unfortunately, there is no completely reliable way to determine the requested type -- a limitation I have also run into. I do not imagine it will be fixed until StructureMap 3.0. However, you might be able to find it by looking at the cx.BuildStack.Root.RequestedType (or other frames on the BuildStack - not always the root). I haven't had great luck with that approach, but it is worth experimenting with.

For your scenario, I would probably just have my consumers accept an IMongDatabase and call GetCollection themselves. It feels a little strange to inject "data" (in the form of IMongCollection) via your IOC.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜