决定从Ninject切换到Simple Injector,我遇到的一个问题是尝试将此代码转换为Simple Injectors等效:
var resolver = new SomeResolver(container);
container.Rebind(typeof(IHubConnectionContext<dynamic>))
.ToMethod(context =>
resolver.Resolve<IConnectionManager>().GetHubContext<PlanHub>().Clients
).WhenInjectedInto<PlanHubService>();
答案 0 :(得分:2)
Rebind
相当于在简单注入者中将Register
设置为true
时使用WhenInjectedInto
。ToMethod
相当于在Simple Injector中使用AllowOverridingRegistrations。Register<T>(Func<T>)
通常等于在简单注入者中使用RegisterConditional
,但与Registration
结合使用时,您将不得不回退到使用{{Lifestyle.CreateRegistration<T>(Func<T>, Container)
创建container.RegisterConditional(
typeof(IHubConnectionContext<dynamic>),
Lifestyle.Transient.CreateRegistration(
() => container.GetInstance<IConnectionManager>().GetHubContext<PlanHub>().Clients,
container),
WhenInjectedInto<PlanHubService>);
1}}。因此,您可以将绑定重写为以下Simple Injector代码:
WhenInjectedInto<T>
其中private static bool WhenInjectedInto<T>(PredicateContext context) =>
typeof(T).IsAssignableFrom(context.Consumer.ImplementationType);
是定义如下的自定义帮助方法:
private void initRealm() {
Realm.init(this);
RealmConfiguration configuration = new RealmConfiguration.Builder()
.schemaVersion(3)
.name("sipradi")
.migration(new RealmMigrationClass())
.build();
Realm.setDefaultConfiguration(configuration);
}
private class RealmMigrationClass implements RealmMigration {
@Override
public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {
RealmSchema schema = realm.getSchema();
if (oldVersion == 2) {
RealmObjectSchema profileUserSchema = schema.get("ProfileUser");
profileUserSchema.addField("test", String.class);
// Delete all other data than `ProfileUser`
for (RealmObjectSchema classSchema : schema.getAll()) {
if (classSchema.getClassName().equals("ProfileUser")) {
continue;
}
realm.delete(classSchema.getClassName());
}
oldVersion++;
}
}
}