Windows 表单应用程序中的 Autofac 容器
Autofac Container in Windows Form Application
我是 IoC 的新手,尤其是 Autofac。有几天我对 Windows 申请表中的 IoC 感到困惑。障碍是如何显示(如:Show、ShowDialog)已注册的表单。而IContainer只能本地访问(私有)Program.cs.
其实,在Windows申请表中可以使用IoC吗?我给出了一个让我困惑的示例代码。
#
# Demo.Core Project
#
namespace Demo.Core.Repository
{
public interface IBaseRepository<T>
{
DbConnection CreateConnection();
IEnumerable<T> Get(IDbTransaction transaction = null, int? commandTimeout = null);
}
public abstract class BaseRepository<T> : IBaseRepository<T> where T : class
{
public DbConnection CreateConnection()
{
return new SqlConnection("Data Source=localhost;User ID=sa;Password=Default!3;Initial Catalog=DemoIoC;");
}
public IEnumerable<T> Get(IDbTransaction transaction = null, int? commandTimeout = null)
{
using (var connection = CreateConnection())
return connection.GetAll<T>(transaction, commandTimeout);
}
}
public interface IUserRepository : IBaseRepository<User> { }
public class UserRepository : BaseRepository<User>, IUserRepository { }
}
namespace Demo.Core.Models
{
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
}
#
# Demo.Winform Project
#
using Demo.Core.Models;
using Demo.Core.Repository;
namespace Demo.Winform
{
static class Program
{
public static IContainer Container;
[STAThread]
static void Main()
{
Container = Configure();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
static IContainer Configure()
{
var builder = new ContainerBuilder();
builder.RegisterType<UserRepository>().As<IUserRepository>();
builder.RegisterType<UserManagerForm>();
return builder.Build();
}
}
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
button1.Click += new EventHandler(delegate (object sender, EventArgs e)
{
using (var container = *** HOW TO GET CONTAINER ? ***)
{
Form manager = container.Resolve<UserManagerForm>();
manager.ShowDialog();
}
});
}
}
public partial class UserManagerForm : Form
{
private readonly IUserRepository repository;
public UserForm(IUserRepository repository) : this()
{
this.repository = repository;
}
public UserForm()
{
InitializeComponent();
}
protected override void OnShown(EventArgs e)
{
base.OnShown(e);
listBox1.ValueMember = "Id";
listBox1.DisplayMember = "Name";
listBox1.DataSource = repository.Get();
}
}
}
我已阅读如何在容器中注册表单类型:Autofac - Register all Windows Forms。但是问题来了,我要如何解析注册的表单和show form?
谢谢。
这对我有用,你只需从容器中获取服务\
static class Program
{
public static IContainer Container;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Container = Configure();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1(Container.Resolve<IWindowsFormsApp3Client>()));
}
static Autofac.IContainer Configure()
{
var builder = new ContainerBuilder();
builder.Register<IWindowsFormsApp3Client>(ctor => new WindowsFormsApp3Client(new Uri("https://localhost:44381"), new CustomLoginCredentials()))
.AsImplementedInterfaces();
// builder.RegisterType<WindowsFormsApp3Client>().As<IWindowsFormsApp3Client>();
builder.RegisterType<Form1>();
return builder.Build();
}
}
public class CustomLoginCredentials : ServiceClientCredentials
{
private string AuthenticationToken { get; set; }
public override async Task ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
// AuthenticationToken = Extensions.GetAppsettingsToken()?.AccessToken;
if (AuthenticationToken != null)
{
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", AuthenticationToken);
}
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
await base.ProcessHttpRequestAsync(request, cancellationToken);
}
}
我是 IoC 的新手,尤其是 Autofac。有几天我对 Windows 申请表中的 IoC 感到困惑。障碍是如何显示(如:Show、ShowDialog)已注册的表单。而IContainer只能本地访问(私有)Program.cs.
其实,在Windows申请表中可以使用IoC吗?我给出了一个让我困惑的示例代码。
#
# Demo.Core Project
#
namespace Demo.Core.Repository
{
public interface IBaseRepository<T>
{
DbConnection CreateConnection();
IEnumerable<T> Get(IDbTransaction transaction = null, int? commandTimeout = null);
}
public abstract class BaseRepository<T> : IBaseRepository<T> where T : class
{
public DbConnection CreateConnection()
{
return new SqlConnection("Data Source=localhost;User ID=sa;Password=Default!3;Initial Catalog=DemoIoC;");
}
public IEnumerable<T> Get(IDbTransaction transaction = null, int? commandTimeout = null)
{
using (var connection = CreateConnection())
return connection.GetAll<T>(transaction, commandTimeout);
}
}
public interface IUserRepository : IBaseRepository<User> { }
public class UserRepository : BaseRepository<User>, IUserRepository { }
}
namespace Demo.Core.Models
{
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
}
#
# Demo.Winform Project
#
using Demo.Core.Models;
using Demo.Core.Repository;
namespace Demo.Winform
{
static class Program
{
public static IContainer Container;
[STAThread]
static void Main()
{
Container = Configure();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
static IContainer Configure()
{
var builder = new ContainerBuilder();
builder.RegisterType<UserRepository>().As<IUserRepository>();
builder.RegisterType<UserManagerForm>();
return builder.Build();
}
}
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
button1.Click += new EventHandler(delegate (object sender, EventArgs e)
{
using (var container = *** HOW TO GET CONTAINER ? ***)
{
Form manager = container.Resolve<UserManagerForm>();
manager.ShowDialog();
}
});
}
}
public partial class UserManagerForm : Form
{
private readonly IUserRepository repository;
public UserForm(IUserRepository repository) : this()
{
this.repository = repository;
}
public UserForm()
{
InitializeComponent();
}
protected override void OnShown(EventArgs e)
{
base.OnShown(e);
listBox1.ValueMember = "Id";
listBox1.DisplayMember = "Name";
listBox1.DataSource = repository.Get();
}
}
}
我已阅读如何在容器中注册表单类型:Autofac - Register all Windows Forms。但是问题来了,我要如何解析注册的表单和show form?
谢谢。
这对我有用,你只需从容器中获取服务\
static class Program
{
public static IContainer Container;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Container = Configure();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1(Container.Resolve<IWindowsFormsApp3Client>()));
}
static Autofac.IContainer Configure()
{
var builder = new ContainerBuilder();
builder.Register<IWindowsFormsApp3Client>(ctor => new WindowsFormsApp3Client(new Uri("https://localhost:44381"), new CustomLoginCredentials()))
.AsImplementedInterfaces();
// builder.RegisterType<WindowsFormsApp3Client>().As<IWindowsFormsApp3Client>();
builder.RegisterType<Form1>();
return builder.Build();
}
}
public class CustomLoginCredentials : ServiceClientCredentials
{
private string AuthenticationToken { get; set; }
public override async Task ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
// AuthenticationToken = Extensions.GetAppsettingsToken()?.AccessToken;
if (AuthenticationToken != null)
{
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", AuthenticationToken);
}
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
await base.ProcessHttpRequestAsync(request, cancellationToken);
}
}