C # Use Spring. NET to implement IOC control inversion and DI dependency injection (Code tutorial ),
Import Common. Logging, Spring. Core
Create user information business interface class:
IUserInfoService. cs
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace SpringNet{ public interface IUserInfoService { string ShowMsg(); }}
Implementation interface:
UserInfoService. cs
Using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; namespace SpringNet {class UserInfoService: IUserInfoService {public string UserName {get; set;} public Person person {get; set;} public string ShowMsg () {return "Hello World! "+ UserName +" Age: "+ person. Age ;}}}
Person. cs
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace SpringNet{ public class Person { private int age; private string name; public int Age { get => age; set => age = value; } public string Name { get => name; set => name = value; } }}
Configure App. config
An example that demonstrates simple IoC features.
Services. xml
An example that demonstrates simple IoC features.
You need to set the xml file attribute to copy to the output directory.
Key code:
IApplicationContext ctx = ContextRegistry.GetContext(); IUserInfoService lister = (IUserInfoService)ctx.GetObject("UserInfoService"); MessageBox.Show(lister.ShowMsg());
Project Structure:
Running result: