我想将IoC与Entity框架和Ninject一起使用.我想我需要Generated Entity类来实现一个接口ICRUD.这是一个演练,展示了如何强制实体框架实现一个接口.我按照指示操作,我的EntityObjectCodeGenerator.cs文件确实显示"ICrud",但没有实现接口.我没有在EntityObjectCodeGenerator.tt下看到任何子类,因为文章说我应该这样做.我收到错误
'BugnetMvc.Models.BugNetEntities'没有实现接口成员'BugnetMvc.Services.ICrud.Update()'
更新
目标是利用实体框架创建可测试的,可扩展的MVC-3内部网,该框架还支持强类型视图和部分视图.根据我迄今为止对Ninject的小经验,我相信我需要使用View本身的服务(假设每个接口可用的CRUD方法)重载我的Controller的构造函数,并为每个局部视图添加一个:
例如
public HomeController(HomeService homeCrudService, PartialViewService1 partialviewService)
Run Code Online (Sandbox Code Playgroud)
Update2
为了清楚并希望帮助他人,代码可以实现如下:
这就是人们如何扩展实体
namespace BugnetMvc.Models//ensure namespace matches entity
{
public partial class Milestone : ICrud<Milestone>//Entity, note the CRUD generic. This gives us a lot of flexibility working with Ninject
{
public bool Create()
{
throw new System.NotImplementedException();
}
public List<Milestone> Read()
{
var milestones = new List<Milestone>();
var result = from a in new BugNetEntities1().Milestones
where a.MilestoneID >= 0
select new { a.Milestone1 };
milestones = result.AsEnumerable() …Run Code Online (Sandbox Code Playgroud) 说,我有这样的类层次结构:
public interface IRepository { }
public class SomeSimpleRepository : IRepository {}
Run Code Online (Sandbox Code Playgroud)
现在我想用其他函数"装饰"SomeSimpleRepository
public class MoreAdvancedRespository : IRepository
{
private readonly IRepository _originalRepository;
public MoreAdvancedRespository(IRepository original)
{ }
}
Run Code Online (Sandbox Code Playgroud)
过了一会又一个......
public class TrickyRepository : IRepository
{
private readonly IRepository _originalRepository;
public TrickyRepository (IRepository original)
{ }
}
Run Code Online (Sandbox Code Playgroud)
现在,我需要完成绑定.在应用程序中,我需要使用MoreAdvancedRespository初始化TrickyRepository的实例.所以,我需要写一些类似的东西:
Bind<IRepository>().To<TrickyRepository>.With ??
Run Code Online (Sandbox Code Playgroud)
在这里我很困惑,我需要以某种方式说,采取MoreAdvancedRespository,但用SomeSimpleRepository初始化它.这是一种依赖关系链,必须针对一个接口进行解析.
有没有人对此提出建议?
所以,我有一个从WCF服务公开的方法:
public GetAllCommentsResponse GetAllComments(GetAllCommentsRequest request)
{
var response = new GetAllCommentsResponse();
using(_unitOfWork)
try
{
Guard.ArgNotNull(request, "request");
var results = _unitOfWork.CommentRepository.Get(d => d.Id > 0).ToArray();
//... Do rest of stuff here
}
catch (Exception ex)
{
response.Success = false;
response.FailureInformation = ex.Message;
Logger.LogError("GetAllComments Method Failed", ex);
}
return response;
}
Run Code Online (Sandbox Code Playgroud)
我有一个全局DataUnitOfWork对象(实现IDisposable),当服务调用进来时,Ninject通过构造函数参数实例化.当调试时,如果我使用
using(_unitOfWork)
Run Code Online (Sandbox Code Playgroud)
超出范围后,_unitOfWork对象立即被释放,然后被Ninject再次调用(尽管它被标记为已丢弃,因此没有任何反应.)如果没有using语句,Ninject将处理处理.
长话短说,这是否有一般的经验法则?在我阅读的所有内容似乎表明永远不会使用它,或者在某些折衷的情况下使用它之后,我一直害怕整个IDisposable的东西,但它总是让我感到困惑.
任何输入都表示赞赏.
哦,当我在这里打字时,为什么在处理时确实有GC.SuppressFinalize()的调用?Dispose和Finalize有何不同?
最近我切换到Ninject 2.0版本并开始收到以下错误:
Error occured: Error activating SomeController More than one matching bindings are available. Activation path: 1) Request for SomeController Suggestions: 1) Ensure that you have defined a binding for SomeController only once.
但是,我无法找到某种复制路径.有时它会发生,有时它不会发生.我正在使用NinjectHttpApplication自动控制器注入.控制器在单独的程序集中定义:
public class App : NinjectHttpApplication
{
protected override IKernel CreateKernel()
{
INinjectModule[] modules = new INinjectModule[] {
new MiscModule(),
new ProvidersModule(),
new RepositoryModule(),
new ServiceModule()
};
return new StandardKernel(modules);
}
protected override void OnApplicationStarted()
{
RegisterRoutes(RouteTable.Routes);
RegisterAllControllersIn("Sample.Mvc");
base.OnApplicationStarted();
}
/* ............. */
}
Run Code Online (Sandbox Code Playgroud)
也许有人熟悉这个错误. …
我正在使用C#,.NET Framework 4.5.1开发ASP.NET Web Api 2.2.
更新我的Web.Api到Ninject 3.2.0后,我收到此错误:
Error activating ModelValidatorProvider using binding from ModelValidatorProvider to NinjectDefaultModelValidatorProvider
A cyclical dependency was detected between the constructors of two services.
Activation path:
3) Injection of dependency ModelValidatorProvider into parameter defaultModelValidatorProviders of constructor of type DefaultModelValidatorProviders
2) Injection of dependency DefaultModelValidatorProviders into parameter defaultModelValidatorProviders of constructor of type NinjectDefaultModelValidatorProvider
1) Request for ModelValidatorProvider
Suggestions:
1) Ensure that you have not declared a dependency for ModelValidatorProvider on any implementations of the service.
2) Consider …Run Code Online (Sandbox Code Playgroud) 我正在尝试创建一个"准系统"Web API项目,该项目使用OWIN中间件,Ninject Depencency Injection,最终将在IIS中托管.我按照文章"与ASP.NET Web.API2,OWIN和Ninject建立联系"中的说明进行了操作:http://www.alexzaitzev.pro/2014/11/webapi2-owin-and-ninject.html,除了我使用了一个空的Web应用程序项目,并且在创建项目时没有勾选"包含Web API引用和文件夹".
当我启动新API并发出页面请求时,我会Ninject.ActivationException抛出以下内容:
Run Code Online (Sandbox Code Playgroud)Server Error in '/' Application. Error activating HttpConfiguration More than one matching bindings are available. Matching bindings: 1) binding from HttpConfiguration to method 2) binding from HttpConfiguration to constant value Activation path: 1) Request for HttpConfiguration Suggestions: 1) Ensure that you have defined a binding for HttpConfiguration only once.
刷新浏览器时,此异常消失了.我真的不明白是什么导致了这个异常.从我的观点来看,在OWIN环境和Ninject中对WebAPI缺乏经验,很难知道问题出在哪里.与Ninject一起......?它在OWIN ......?是在WebAPI ......?
这是我的Startup.cs文件的内容:
using System.Web.Http;
using LHD.API_2;
using Microsoft.Owin;
using Microsoft.Owin.Security.OAuth;
using Ninject.Web.Common.OwinHost;
using Ninject.Web.WebApi.OwinHost;
using Owin; …Run Code Online (Sandbox Code Playgroud) 我正在学习DI,最近做了我的第一个项目.
在这个项目中,我实现了存储库模式.我有接口和具体实现.我想知道是否有可能将我的接口的实现构建为"插件",我的程序将动态加载的dll.
所以程序可以随着时间的推移而不需要重建它,你只需将dll放在"plugins"文件夹,更改设置和voilá!
这可能吗?Ninject可以帮助解决这个问题吗?
只是试着继续关注IOC原则.
Q1:静态方法 - 是否应将带有静态辅助方法的util类与IOC连接?
例如,如果我有一个带有许多静态方法的HttpUtils类,我应该尝试通过IOC将它传递给其他业务逻辑类吗?
关注这个问题可能是:
Q2:Singletons - 通过Logger.getInstance()类型调用,通常可以访问它的内容.您是否通常将其保留原样,并且不使用IOC将记录器注入需要它的业务类?
问题3:静态类 - 我还没有真正使用过这个概念,但如果你转向基于IOC的方法,那么你是否有任何指导方针可以解决这个问题.
提前致谢.
我正在使用附加的图像来解释我的意思.
我有一些由NInject管理的课程.其中一些具有一些单例实例,而另一些则处于瞬态范围.在图像中,蓝色矩形是单色,红色是瞬态的.处理器依赖于其他类或实例.
我希望每次都使用kernel.Get来获取Processor的实例.但是,每次我想为处理器使用的对象使用不同的值.请参见图像中的Action1和Action2.代码不是真实的,只是为了解释.
有没有现成的方法可以满足我的需求?
我已经创建了一个新的MVC Web应用程序,并且我引用了Ninject.dll,Ninject.Web.Common.dll和Ninject.Web.MVC.dll.
的Global.asax.cs:
public class MvcApplication : NinjectHttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new
{
controller = "Home",
action = "Index",
id = UrlParameter.Optional
});
}
protected override IKernel CreateKernel()
{
var kernel = new StandardKernel();
kernel.Load(Assembly.GetExecutingAssembly());
return kernel;
}
protected override void OnApplicationStarted()
{
base.OnApplicationStarted();
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
}
Run Code Online (Sandbox Code Playgroud)
App_start\NinjectWebCommon:
public static class NinjectWebCommon
{
private …Run Code Online (Sandbox Code Playgroud) ninject ×10
c# ×5
.net ×3
asp.net-mvc ×2
decorator ×1
idisposable ×1
instance ×1
owin ×1
plugins ×1
static ×1