I am developing a collection of small games using WPF with C# but have been having real difficulty in being able to load and unload each game into my main viewer application.
The structure of my program is I have a main view application GameViewer.EXE which basically consists of a Frame object to view pages.
Each game is a custom class GamePage.CS, shown below:
Expand|Select|Wrap|Line Numbers
- GameLibrary.DLL
- namespace GameLibrary
- {
- public class GamePage : Page
- {
- public Guid GameID;
- public string GameName;
- public string Description;
- public virtual void PauseGame(){}
- public event GameEndArgsEventHandler GameEnd;
- protected void OnGameEnd(GameEndArgs e)
- {
- if (GameEnd != null)
- GameEnd(this, e);
- }
- }
- public class GameEndArgs : EventArgs
- {
- public double Score;
- public bool Finished;
- public int Level = 1;
- }
- }
I also have a ControlLibrary.DLL , which contains a collection of stylized controls, i.e. customs, sliders, etc., which is used in all games and the main interface GameViewer.EXE.
The structure of the application is:
Expand|Select|Wrap|Line Numbers
- Home\
- GameViewer.EXE
- GameLibrary.DLL
- ControlLibrary.DLL
- Games\
- Game1\
- game1.DLL
- game1Dependency1.DLL
- game1Dependency2.DLL
- Game2\
- game2.DLL
- Game3\
- game3.DLL
- image\
- ...
- Game n
My trouble is being able to load then successfully unload each game DLL into my main viewer. I have been reading dozen of threads, but I cannot seem to get anything to work. I am trying to create a new AppDomain load the assembly in there and create the GamePage object.
- I can then unload the appdomain when the game is finished, but on repeated opening and closing the game I see the memory usuage shoot up, so something is going wrong.
- I have also tried creating a separate loader, using the MarshalByRefObject, but on returning a GamePage I am told that GamePage is not Serializable.
This is my current attempt:
In the GameLibrary.DLL I have:
Expand|Select|Wrap|Line Numbers
- namespace GameLibrary
- {
- [Serializable]
- public class Factory
- {
- public GamePage CreateGamePageObject(string path, string typename)
- {
- return Activator.CreateInstanceFrom(path, typename).Unwrap() as GamePage;
- }
- }
- }
Expand|Select|Wrap|Line Numbers
- private AppDomain domain =null;
- void LoadGame(string GameFile)
- {
- domain = AppDomain.CreateDomain("Remote Load");
- ObjectHandle oh = domain.CreateInstance("GameLibrary", "GameLibrary.Factory");
- Object obj = oh.Unwrap();
- GameLibrary.Factory f = obj as GameLibrary.Factory;
- GameLibrary.GamePage addIn=null;
- FileInfo fi = new FileInfo(GameFile);
- addIn =f.CreateGamePageObject(fi.FullName, fi.Name.Substring(0, fi.Name.Length - 4) + ".Page1");
- MainFrame.Content = addIn;
- }
- void UnloadGame()
- {
- MainFrame.Content = null;
- AppDomain.Unload(domain);
- }
I would greatly appreciate any help and suggestions.