V
V
Vyacheslav Onufriyuk2016-06-26 17:03:11
Software design
Vyacheslav Onufriyuk, 2016-06-26 17:03:11

How to implement Inversion of Control in Rust?

Hello.
I am slowly learning Rust, and decided to write a small application on it along the way in order to better understand the principles of development on it. My problem arose almost immediately. Let's take for example such a spherical architecture in a vacuum, without the characteristic growing complications:

trait Some {
  fn get_id(&self) -> int;
}

trait SomeFactory {
  fn create_some(&self) -> &Some
}

struct MyApp {
  factory: &SomeFactory
}

impl MyApp {
  fn new(f: &SomeFactory) -> MyApp {
    MyApp {
      factory: f
    }
  }
}

Without an IoC container, I can do something like this:
fn bootstrap() -> MyApp {
  let factory = MyFactory::new();
  MyService::new(&factory)
}

fn main() {
  let app = bootstrap();
  app.run();
}

But, of course, I don't want to have to go into bootstrap and manually redo the initialization of the application every time I change the list of parameters in ::new. Here is what I want to achieve:
fn bootstrap() -> IoC {
  let IoC = IoC::new();
  IoC.Register<SomeFactory, MyFactory>();
  IoC.Register<SomeApp, MyApp>();

  IoC
}

fn main() {
  let IoC = bootstrap();
  let app = IoC.Resolve<SomeApp>();
  app.run();
}

In principle, it doesn't matter whether it will be a macro or not. Although, an implementation that will run at compile time rather than runtime is even preferable.
Are there already any practices, or maybe ideas on how to do it better in rast?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question