English 中文(简体)
利用反思和结构地图
原标题:Using Reflection and Structure Map

I m 采用结构图,自动向我的保存构造注入数据。 I m给出了名字(例如“项目1”),我需要动态地创建项目保存人的榜样。

I m 采用标准命名公约,因此我知道“项目1DataContext”。 我曾设法利用思考,对我的“项目1DataContext”进行论证,但是它属于一种物体类型。 问题在于,我需要把项目1DataContext Object带入我的保存人,以树立一个榜样。 我如何利用思考来做到这一点? 能否通过某种手段来投放物体?

Assembly myDataContextAssembly = typeof(SomeTypeInTheAssembly).Assembly;
Type dataContextType = myDataContextAssembly.GetType(ProjectName + "DataContext");
object dataContext = Activator.CreateInstance(dataContextType);    
// I need to cast the data context here
IRepository<Project1DataContext> = new Repository<Project1DataContext>(dataContext)

In the mean time, I will use an if statement, but this is not a viable solution if I have 100+ projects. I need to do this using reflection and ideally having structure map determine the types and injecting them for me.

最佳回答

鉴于我从所提供的信息中了解到的情况,你想在你将这种数据转至保存人和保存机构通用类别之前,将数据内容投向真正的一类。 指的是你想要做到特定<>。 can/em>在运行期间将其具体化,但not则通过作为一般论点的类型物体予以通过。 此外,你不能在此依赖一般的推论,因为只是在汇编时间才这样做。

I will suppose that your method returns an IRepository or Respository (without generic parameters).

Here is what you need to do: Create a concrete type for Repository<> using dataContextType and then use that concrete type to create a Repository object that you cast to Repository and then return it.

        Assembly myDataContextAssembly = typeof(SomeTypeInTheAssembly).Assembly;
        Type dataContextType = myDataContextAssembly.GetType(ProjectName + "DataContext");
        Type concreteRepositoryType = typeof(Generic<>).MakeGenericType(dataContextType);
        Repository repository = (Repository)System.Activator.CreateInstance(concreteRepositoryType);
        return repository;
问题回答

暂无回答




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...