我需要将StructureMap代码转换为Ninject (以支持我的宿主提供商,因为它们只支持在中等信任下运行的应用程序)。我在StructureMap中的基本寄存器是:
ObjectFactory.Initialize(x =>
{
x.For<IDbConnection>()
.HttpContextScoped()
.Use(() =>
{
var constr = ConfigurationManager
.ConnectionStrings["conn"].ConnectionString;
var conn = new SqlConnection(constr);
conn.Open();
return conn;
});
x.FillAllPropertiesOfType<IDbConnection>();
x.For<ICurrent>().Use<Current>();
x.For<ILogger>().Use<Logger>();
x.For<IMembershipService>().Use<SpaceMembership>();
x.For<IFormsAuthenticationService>()
.Use<FormsAuthenticationService>();
x.Scan(sc =>
{
sc.Assembly("Space360.DB");
sc.AddAllTypesOf(typeof(IRepository<>));
sc.WithDefaultConventions();
});
});发布于 2013-01-29 19:28:58
它看起来像这样:
// IDbConnection binding
Bind<IDbConnection>().ToMethod(x => {
var constr = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
var conn = new SqlConnection(constr);
conn.Open();
return conn;})
.InRequestScope();
// ommited fill all properties of type
Bind<ICurrent>().To<Current>(); // .InRequestScope() - just suggestion
Bind<ILogger>().To<Logger>();
Bind<IMembershipService>().To<SpaceMembership>();
Bind<IFormsAuthenticationService>().To<FormsAuthenticationService>();
// for this: Ninject.Extensions.Conventions has to be referenced
Bind(x=> x.From("Space360.DB")
.SelectAllClasses().InheritedFrom<IRepository>()
.BindDefaultInterface()
// .Configure(b => b.InRequestScope())
);恐怕目前还没有类似于FillAllPropertiesOfType的方法的内置版本。您必须使用[Inject]属性标记所有依赖属性(但它会将您的类绑定到Ninject.Core),或者您可以尝试本文中描述的方法:
Ninject 3.0 Property Injection Without [Inject] Attribute
基本上,它创建了IInjectionHeuristic的实现-- Ninject组件,它连接到了ninject内核,因此它知道如何解释启发式方法。ShouldInject方法中的注入规则如下:
请注意,还有用于隐式注入记录器的 (当前支持Log4Net和NLog)。
https://stackoverflow.com/questions/14553127
复制相似问题