开发者

Database Storage of Dynamic Methods in C#

How can I store C# methods in a sql server instance to be loaded and开发者_如何学编程 run dynamically (at runtime) at a later date?

I am about to begin a production test project at work where I would like the appropriate test methods for the product to be loaded at runtime.

I have looked at Reflection.Emit DynamicMethod briefly but it is not serializable.

Any suggestions or alternative routes would be appreciated.


Serialising classes does not serliase any code it just serialises data and the reloads that data into the properties of the class when it is deserialised. Any methods on the class are just the same as if you had just instantiated the class manually. Trying to serialise actual code to a database and then somehow compile it into a method from at run time is a pretty whacky and exotic thing to do and i am strugling to understand how it would be useful in the context of testing. If you really really want to store the source code in the database you would be better off storing it as text, retreiving it into a text file then programtically compiling it. However this is what source control and build systems are for such as Subversion and Nant, so you would arguably be reinventing the wheel.

Further to your last comment i think a good pattern for what you require would be dependency injection. You create an interface (e.g. ITester) that defines the contract for a test, a simple one would be a test method that returns a bool for pass and fail. You write your testing program as normal, but your test method takes a class that implements the ITest interface. The class that implements the ITester interface is reponsible for the specific test implementation and actually carries out the test. THe rest of the system does not care what the test is or how it is carried out, it simply runs a test method that returns true or false.

That way all you have to do to create a new test implementation is create a new class that implements ITester. If you need to change a test implementation you just alter the particular class and redeploy. If you compile each tester class into it's own DLL, you can store these as binary data in the database. You can then extract them from the database and load them dynamically using System.Reflection.Assembly.Load. Note, this is not serialisation, you are storing the binary assembly file in the datbase.

What you end up with is a system that decides what test it needs to run, queries the database for the relevent DLL file that can run the test code, then dynamically loads and executes the DLL at run time.


Out of interest, if you use Expression<> trees for your methods, there is a project on the go to serialize these - see the SO post here

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜